Cheat sheet · Back end and data

Node.js cheat sheet

Run scripts, use modules, read files, build a small server and manage packages with npm.
Sections
6
Items
26
Area
Back end and data
Download
PNG, PDF

Cheat sheet

Node.js

Run scripts, use modules, read files, build a small server and manage packages with npm.

/blogs

Run and packages

node app.js
Run a file
npm init -y
Create package.json
npm install <name>
Add a package
npm install -D <name>
Add a package used only while developing
npm run <script>
Run a script from package.json
npx <tool>
Run a package without installing it

Modules

import fs from "node:fs"
Import (ES modules; set "type": "module")
export default fn / export { a, b }
Share things from a file
const x = require("x")
The older CommonJS way
import.meta.url
Address of the current file (ES modules)

Files and paths

await fs.promises.readFile(p, "utf8")
Read a file as text
await fs.promises.writeFile(p, text)
Write a file
await fs.promises.readdir(dir)
List a folder
path.join(a, b)
Join path parts safely
path.extname("a.txt")
".txt"

Process and environment

process.env.PORT
Read an environment variable
process.argv
Command-line arguments
process.exit(1)
Stop with an error code
process.on("unhandledRejection", fn)
Catch promises nobody handled

A small server

http.createServer((req, res) => { })
Handle each request
res.writeHead(200, { "Content-Type": "text/plain" })
Set status and headers
res.end("Hello")
Send the body and finish
server.listen(3000)
Start listening on a port

Events and streams

emitter.on("event", fn)
Listen for an event
emitter.emit("event", data)
Fire the event
fs.createReadStream(p).pipe(res)
Send a big file in small pieces

Remember

  • Never block the main thread with a long loop. Use async functions for files and network.
  • Keep secrets in environment variables, and never commit a .env file.

Learn it properly

A cheat sheet helps you remember. These lessons explain the ideas step by step, with examples.

More cheat sheets

All cheat sheets →