TechSchool
Home / Cheat sheets / Node.js

Node.js cheat sheet

96 one-line examples for Node.js. Open it while you code, or print it and keep it near the keyboard. Free, with no signup and no ads.

Run and Import

CodeWhat it does
node app.jsRun a file with Node.
node --versionShow the Node version.
nodeOpen the REPL.
.exitLeave the REPL.
const fs = require('fs')Load a built-in module.
import fs from 'fs'Load a module in ES mode.
require('./math.js')Load a local file.
module.exports = addExport one value.
exports.add = addExport a named value.
__dirnameGive the folder path.
__filenameGive the file path.
process.argvRead command line arguments.

Console and Process

CodeWhat it does
console.log('hi')Print a value.
console.error('bad')Print to stderr.
console.table(rows)Print data as a table.
process.env.PORTRead an environment variable.
process.exit(1)Stop with a failure code.
process.cwd()Show the current folder.
process.platformShow the operating system name.
process.pidShow the process ID.
process.stdinRead input from the user.
process.stdout.write('x')Write text without a newline.
setTimeout(fn, 1000)Run a function after a delay.
setInterval(fn, 1000)Run a function many times.

Files with fs

CodeWhat it does
fs.readFileSync('a.txt','utf8')Read a file as text.
fs.writeFileSync('a.txt', 'hi')Write text to a file.
fs.appendFileSync('a.txt', 'hi')Add text to a file.
fs.existsSync('a.txt')Check that a file exists.
fs.unlinkSync('a.txt')Delete a file.
fs.mkdirSync('data')Make a folder.
fs.readdirSync('.')List folder contents.
fs.renameSync('a','b')Rename a file.
fs.statSync('a.txt').sizeShow the file size.
fs.readFile('a.txt','utf8',cb)Read a file with a callback.
await fs.promises.readFile('a')Read a file with await.
path.join('a', 'b.txt')Build a safe file path.

Async and Promises

CodeWhat it does
async function load() {}Declare an async function.
await fetch(url)Wait for a promise result.
Promise.all([a, b])Wait for many promises.
Promise.race([a, b])Take the first promise result.
new Promise((ok, bad) => {})Create a promise.
try { await f() } catch (e) {}Catch an async error.
setImmediate(fn)Run a function after this tick.
queueMicrotask(fn)Run a function in the microtask queue.
await new Promise(r => setTimeout(r, 500))Pause for half a second.
Promise.resolve(1)Make a resolved promise.
Promise.reject(new Error('x'))Make a rejected promise.
await Promise.allSettled(list)Wait for all results and errors.

HTTP Server

CodeWhat it does
http.createServer(handler)Create an HTTP server.
server.listen(3000)Start the server on port 3000.
res.writeHead(200, {'Content-Type':'text/plain'})Send a status and headers.
res.end('hello')Send the response body.
req.methodRead the request method.
req.urlRead the request path.
req.headers.hostRead a request header.
res.statusCode = 404Set the status code.
res.setHeader('X', '1')Set one response header.
req.on('data', chunk => {})Read request body chunks.
req.on('end', () => {})Run code when the body ends.
server.close()Stop the server.

JSON and Errors

CodeWhat it does
JSON.parse(text)Turn text into an object.
JSON.stringify(obj)Turn an object into text.
JSON.stringify(obj, null, 2)Format JSON with two spaces.
throw new Error('bad')Throw an error.
try { f() } catch (e) {}Catch an error.
e.messageRead the error text.
e.stackRead the error trace.
Error.captureStackTrace(e)Capture a stack trace.
typeof valueCheck the value type.
Array.isArray(value)Check for an array.
Number.isInteger(n)Check for a whole number.
Object.keys(obj)List the object keys.

npm and Packages

CodeWhat it does
npm init -yCreate a package.json file.
npm install expressAdd a package.
npm install -D nodemonAdd a dev package.
npm uninstall expressRemove a package.
npm run startRun a script.
npm updateUpdate packages to allowed versions.
npm listList installed packages.
npx create-react-app appRun a package without install.
npm ciInstall exact versions from the lock file.
npm auditCheck packages for known risks.
node_modulesHold the installed packages.
package-lock.jsonLock the exact package versions.

Timers and Events

CodeWhat it does
clearTimeout(id)Stop a timeout.
clearInterval(id)Stop an interval.
const e = new EventEmitter()Create an event emitter.
e.on('save', fn)Listen for an event.
e.emit('save', data)Send an event.
e.once('save', fn)Listen one time only.
e.off('save', fn)Remove a listener.
e.removeAllListeners()Remove all listeners.
process.on('exit', fn)Run code on process exit.
process.on('uncaughtException', fn)Handle an uncaught error.
require('events').once(e, 'x')Wait for one event.
e.listenerCount('save')Count the listeners.
More on TechSchool
See the Node.js interview questions Python JavaScript TypeScript HTML CSS React Vue 3 Java PHP C C++ C# Go SQL MongoDB Redis Linux Git Docker Data Structures