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
| Code | What it does |
|---|---|
node app.js | Run a file with Node. |
node --version | Show the Node version. |
node | Open the REPL. |
.exit | Leave 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 = add | Export one value. |
exports.add = add | Export a named value. |
__dirname | Give the folder path. |
__filename | Give the file path. |
process.argv | Read command line arguments. |
Console and Process
| Code | What it does |
|---|---|
console.log('hi') | Print a value. |
console.error('bad') | Print to stderr. |
console.table(rows) | Print data as a table. |
process.env.PORT | Read an environment variable. |
process.exit(1) | Stop with a failure code. |
process.cwd() | Show the current folder. |
process.platform | Show the operating system name. |
process.pid | Show the process ID. |
process.stdin | Read 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
| Code | What 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').size | Show 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
| Code | What 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
| Code | What 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.method | Read the request method. |
req.url | Read the request path. |
req.headers.host | Read a request header. |
res.statusCode = 404 | Set 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
| Code | What 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.message | Read the error text. |
e.stack | Read the error trace. |
Error.captureStackTrace(e) | Capture a stack trace. |
typeof value | Check 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
| Code | What it does |
|---|---|
npm init -y | Create a package.json file. |
npm install express | Add a package. |
npm install -D nodemon | Add a dev package. |
npm uninstall express | Remove a package. |
npm run start | Run a script. |
npm update | Update packages to allowed versions. |
npm list | List installed packages. |
npx create-react-app app | Run a package without install. |
npm ci | Install exact versions from the lock file. |
npm audit | Check packages for known risks. |
node_modules | Hold the installed packages. |
package-lock.json | Lock the exact package versions. |
Timers and Events
| Code | What 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. |