by DannyUpdated 9 sections

Examples use ES modules and Node.js 22 or later.

Download the PDF

Run code


_10
node app.js
_10
node --watch app.js # restart on change
_10
node --env-file=.env app.js
_10
node --run dev # a package.json script
_10
node -e "console.log(1 + 1)"

npm


_10
npm init -y
_10
npm install express # add a dependency
_10
npm install -D vitest # dev dependency
_10
npm uninstall express
_10
npm ci # clean install from lock
_10
npm outdated
_10
npx 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


_10
import fs from 'node:fs/promises';
_10
import path from 'node:path';
_10
import { helper } from './helper.js'; // keep .js
_10
_10
const here = import.meta.dirname; // folder
_10
const file = import.meta.filename; // this file

Files


_10
const text = await fs.readFile('in.txt', 'utf8');
_10
await fs.writeFile('out.txt', text);
_10
await fs.mkdir('dist', { recursive: true });
_10
const names = await fs.readdir('src');
_10
await fs.rm('tmp', { recursive: true, force: true });
_10
path.join(here, 'data', 'a.json');

Environment and process


_10
const port = Number(process.env.PORT ?? 3000);
_10
process.argv.slice(2); // command line args
_10
process.exit(1); // stop with failure
_10
process.on('SIGINT', () => shutDown());

HTTP server


_10
import http from 'node:http';
_10
_10
http.createServer((req, res) => {
_10
res.writeHead(200, { 'Content-Type': 'application/json' });
_10
res.end(JSON.stringify({ ok: true }));
_10
}).listen(3000);

Fetch and timers


_10
const res = await fetch('https://api.example.com');
_10
const data = await res.json();
_10
_10
import { setTimeout as wait } from 'node:timers/promises';
_10
await wait(1000);

Built-in test runner


_10
import { test } from 'node:test';
_10
import assert from 'node:assert/strict';
_10
_10
test('adds', () => {
_10
assert.equal(1 + 1, 2);
_10
});

Run every test file with node --test.