Node.js
Node.js and npm for scripts and small servers: running code, modules, files, HTTP, async code and packages.
Run and manage
node app.jsRun a script
node --watch app.jsRestart when a file changes
node -e "console.log(process.version)"Run one line of code
node --testRun the built-in test runner on *.test.js files
node --inspect app.jsStart with the debugger listening (open chrome://inspect)
npm
npm init -yCreate a package.json
npm install expressAdd a dependency (npm i -D for dev tools)
npm ciInstall exactly what package-lock.json says (use in CI and Docker)
npm run buildRun a script from package.json
npm outdated | npm auditPackages with newer versions, and known vulnerabilities
npx prettier --write .Run a tool without installing it globally
{ "scripts": { "start": "node server.js", "test": "node --test" } }Scripts in package.json: npm start, npm test
Modules
const fs = require("node:fs");CommonJS: load a module (built-ins have the node: prefix)
import { readFile } from "node:fs/promises";ES modules: use "type": "module" in package.json or a .mjs file
module.exports = { add }; | export const add = (a, b) => a + b;Export from CommonJS / from an ES module
const path = require("node:path"); path.join(__dirname, "data", "a.json")Build paths that work on every system
Files and process
const text = await fs.promises.readFile("a.txt", "utf8");Read a file
await fs.promises.writeFile("out.json", JSON.stringify(data, null, 2));Write a file
JSON.parse(text) | JSON.stringify(obj)Text to object and back
process.argv.slice(2)The command-line arguments
process.env.PORT || 3000An environment variable with a default
process.exit(1)Stop with an error code (0 means success)
Async code
const data = await fetch(url).then((r) => r.json());Fetch JSON (fetch is built in)
const [a, b] = await Promise.all([getA(), getB()]);Run two things at the same time and wait for both
try { await work(); } catch (err) { console.error(err.message); }Handle a failure in async code
setTimeout(() => console.log("later"), 1000);Run something after a delay (milliseconds)
process.on("unhandledRejection", (e) => { console.error(e); process.exit(1); });Do not let a forgotten rejection pass silently
A small HTTP server
const http = require("node:http"); http.createServer((req, res) => { res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify({ ok: true, path: req.url })); }).listen(process.env.PORT || 3000);A server with no dependencies
curl -s localhost:3000/healthTry it from another terminal
res.writeHead(404); res.end("not found");Reply with a status code
process.on("SIGTERM", () => server.close(() => process.exit(0)));Shut down cleanly when a container stops
Nothing matches that search.
Cheatsheet for the Node.js path · Deboistech · All cheatsheets