Repository navigation
nodejs compatibility_us
English · 中文
NekoJS ships a set of common Node.js modules, such as fs, path and buffer. You use them the same way as in Node.js, with import or require.
NekoJS is not Node.js, though. Only the modules in the table below exist, and some of them cover only the commonly used parts.
| Module | Use it for |
|---|---|
fs, fs/promises
|
Reading and writing files, in sync, callback and Promise styles |
path |
Joining and splitting paths |
buffer |
Binary data with Buffer
|
timers, timers/promises
|
setTimeout, setInterval, setImmediate
|
events |
EventEmitter |
util |
Helpers such as format, inspect and promisify
|
assert, assert/strict
|
Assertions |
test |
Test framework, only in test_scripts
|
crypto |
randomUUID, randomBytes, createHash, createHmac, timingSafeEqual
|
os |
Operating system information |
process |
Process information such as process.env and process.cwd()
|
module |
createRequire, builtinModules, isBuiltin
|
The node: prefix is optional: import fs from 'node:fs' and import fs from 'fs' are the same.
Buffer, process, the timer functions such as setTimeout, plus queueMicrotask, atob, btoa and performance.now() are globals. You do not need to import them.
import fs from 'node:fs'
import fsp from 'node:fs/promises'
// Sync style
fs.mkdirSync('nekojs/data', { recursive: true })
fs.writeFileSync('nekojs/data/note.txt', 'hello')
console.info(fs.readFileSync('nekojs/data/note.txt', 'utf8')) // hello
console.info(fs.existsSync('nekojs/data/note.txt')) // true
console.info(fs.readdirSync('nekojs/data')) // [ 'note.txt' ]
// Promise style
await fsp.appendFile('nekojs/data/note.txt', ' world')Other common functions such as statSync, copyFileSync, renameSync, rmSync and unlinkSync are there too. The callback style, fs.readFile(path, callback), also works.
Relative paths start from the game folder, not from the script's folder. That is why the example writes nekojs/data/....
If you only want to store a little JSON,
JsonIOis simpler. See Data and state.
import path from 'node:path'
path.join('a', 'b', 'c.txt') // 'a/b/c.txt'
path.extname('a.txt') // '.txt'
path.basename('/x/y/a.txt') // 'a.txt'
path.resolve('a', 'b') // an absolute pathimport { setTimeout as delay } from 'node:timers/promises'
// Global functions, no import needed
const id = setTimeout(() => console.info('one second later'), 1000)
clearTimeout(id)
// Promise style
await delay(1000)
console.info('waited one second')How they differ from Node.js:
- Callbacks run during a game tick, so timing is not exact to the millisecond.
-
setTimeoutreturns a number. There is no.ref()or.unref(). Cancel it withclearTimeout(id). -
Startup scripts cannot use
setIntervalor asetTimeoutwith a delay above 0; it throws an error.setTimeoutwith a delay of 0 andsetImmediateare fine. - At most 1024 timers can be pending at once. Clear the ones you no longer need.
- When scripts reload, the old scripts' timers are cancelled.
Write tests in nekojs/test_scripts/:
// test_scripts/math_test.js
import test from 'node:test'
import assert from 'node:assert/strict'
test('addition', () => {
assert.strictEqual(1 + 1, 2)
})
test('async test', async () => {
const result = await Promise.resolve({ success: true })
assert.ok(result.success)
})Run them with /nekojs test. Results go to logs/nekojs/test.log. test.skip, test.only, test.todo, describe and before / after / beforeEach / afterEach are available too.
node:test works only in test scripts. Anywhere else it throws node:test is only available in test_scripts. Use /nekojs test to run these files. node:assert works everywhere.
const buf = Buffer.from('hello', 'utf8')
console.info(buf.length) // 5
console.info(buf.toString('hex')) // 68656c6c6fFor safety, scripts can only reach some files:
| Operation | Allowed where |
|---|---|
| Read | Any file inside the game folder |
| Create, write, delete, rename | Only files inside nekojs/
|
Write to nekojs/config/
|
Never |
| Create symbolic links | Never |
Anything outside these limits throws an error:
import fs from 'node:fs'
fs.writeFileSync('nekojs/data/x.txt', 'ok') // allowed: inside nekojs/
fs.writeFileSync('options.txt', 'oops') // error: outside nekojs/If you really need to write outside nekojs/, set allowFsWriteOutsideNekojs = true in nekojs/config/engine.toml and restart the game. Scripts can then write anywhere inside the game folder. Writing outside the game folder or to nekojs/config/ is still refused. See Configuration.
You can use pure-JavaScript npm packages by putting them in nekojs/node_modules/. See Module system for how and for the limits.
In short:
- The
mainandexportsfields ofpackage.jsonare not read. If a package's entry is notindex.js, use the full path. - Packages with native code (such as
sharporbetter-sqlite3) do not work. - A package that needs Node APIs beyond the list above will not run.
-
process.exit()does not quit the game. It logs a warning and the script keeps running. -
process.versions.nodeis a fixed version string so that some packages recognise the environment. It does not mean Node.js is running. -
process.chdir()changes wherefsrelative paths start. It does not affect relative paths inimport/require. -
process.nextTick()does not run in exactly the same order as in Node.js. Do not rely on its order relative to Promises. - There are no
http,net,child_processorworker_threadsmodules.
-
Module system: multiple files, npm packages and
java:imports. - Data and state: an easier way to save data.
-
Commands:
/nekojs testand other commands.
Previous: MixinJS (experimental) · Contents · Next: Plugin development
- 首页 / Home · 中文 · EN
- 平台与兼容性 / Platforms and compatibility · 中文 · EN
- 快速开始 / Quick start · 中文 · EN
- 配置参考 / Configuration · 中文 · EN
- 常见问题 / FAQ · 中文 · EN
- 脚本基础 / Script basics · 中文 · EN
- 脚本 API 约定 / Script API conventions · 中文 · EN
- 脚本属性 / Script properties · 中文 · EN
- 全局绑定 / Global bindings · 中文 · EN
- 数据、状态与持久化 / Data, state and persistence · 中文 · EN
- Python 脚本 / Python scripts · 中文 · EN
- Python 特性清单 / Python feature support · 中文 · EN
- 事件参考 / Event reference · 中文 · EN
- AI 辅助脚本编写 / AI-assisted authoring · 中文 · EN
- 命令 / Commands · 中文 · EN
- 错误与日志参考 / Error and log reference · 中文 · EN
- 客户端绘制与后处理 / Client rendering and post effects · 中文 · EN
- 版本化脚本包 / Versioned script packs · 中文 · EN
- 配方系统 / Recipe system · 中文 · EN
- 注册新内容 / Registering new content · 中文 · EN
- 模块系统 / Module system · 中文 · EN
- TypeScript 与 JSX / TypeScript and JSX · 中文 · EN
- JSX 客户端 UI / JSX client UI · 中文 · EN
- MixinJS(实验性) / MixinJS (experimental) · 中文 · EN
- Node.js 兼容 / Node.js compatibility · 中文 · EN