Examples use ES modules and Node.js 22 or later.
Run code
_10node app.js_10node --watch app.js # restart on change_10node --env-file=.env app.js_10node --run dev # a package.json script_10node -e "console.log(1 + 1)"
npm
_10npm init -y_10npm install express # add a dependency_10npm install -D vitest # dev dependency_10npm uninstall express_10npm ci # clean install from lock_10npm outdated_10npx create-vite@latest # run without installing
package.json
_10{_10 "type": "module",_10 "scripts": {_10 "dev": "node --watch src/index.js",_10 "test": "node --test"_10 },_10 "engines": { "node": ">=22" }_10}
Modules
_10import fs from 'node:fs/promises';_10import path from 'node:path';_10import { helper } from './helper.js'; // keep .js_10_10const here = import.meta.dirname; // folder_10const file = import.meta.filename; // this file
Files
_10const text = await fs.readFile('in.txt', 'utf8');_10await fs.writeFile('out.txt', text);_10await fs.mkdir('dist', { recursive: true });_10const names = await fs.readdir('src');_10await fs.rm('tmp', { recursive: true, force: true });_10path.join(here, 'data', 'a.json');
Environment and process
_10const port = Number(process.env.PORT ?? 3000);_10process.argv.slice(2); // command line args_10process.exit(1); // stop with failure_10process.on('SIGINT', () => shutDown());
HTTP server
_10import http from 'node:http';_10_10http.createServer((req, res) => {_10 res.writeHead(200, { 'Content-Type': 'application/json' });_10 res.end(JSON.stringify({ ok: true }));_10}).listen(3000);
Fetch and timers
_10const res = await fetch('https://api.example.com');_10const data = await res.json();_10_10import { setTimeout as wait } from 'node:timers/promises';_10await wait(1000);
Built-in test runner
_10import { test } from 'node:test';_10import assert from 'node:assert/strict';_10_10test('adds', () => {_10 assert.equal(1 + 1, 2);_10});
Run every test file with node --test.