AI Generate Node.js docs instantly

Node.js Cheat Sheet

Quick reference guide with copy-paste ready code snippets

Try DocuWriter Free

Async Patterns

4 snippets

Callbacks, promises, and async/await

Async/Await

async function fetchData() {
  try {
    const res = await fetch('https://api.example.com');
    const data = await res.json();
    return data;
  } catch (err) {
    console.error(err);
  }
}

Promise.all

const [users, posts] = await Promise.all([
  fetch('/api/users').then(r => r.json()),
  fetch('/api/posts').then(r => r.json()),
]);

Event Emitter

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('data', (msg) => console.log(msg));
emitter.emit('data', 'hello');

Timers

setTimeout(fn, 1000);      // After 1s
setInterval(fn, 5000);     // Every 5s
setImmediate(fn);          // Next iteration
process.nextTick(fn);      // Before next I/O

File System

4 snippets

Reading and writing files

Read File

const fs = require('fs/promises');
const data = await fs.readFile('file.txt', 'utf8');
const json = JSON.parse(await fs.readFile('data.json', 'utf8'));

Write File

await fs.writeFile('out.txt', 'Hello');
await fs.appendFile('log.txt', 'New line\n');

Streams

const { createReadStream, createWriteStream } = require('fs');
const { pipeline } = require('stream/promises');
await pipeline(
  createReadStream('input.txt'),
  createWriteStream('output.txt')
);

Directory Ops

await fs.mkdir('dir/sub', { recursive: true });
const files = await fs.readdir('.', { withFileTypes: true });
const stats = await fs.stat('file.txt');

HTTP Server

3 snippets

Built-in HTTP module

Basic Server

const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ message: 'Hello' }));
});
server.listen(3000);

URL Parsing

const url = new URL(req.url, 'http://localhost');
const id = url.searchParams.get('id');
const path = url.pathname;

Fetch (built-in)

const res = await fetch('https://api.example.com', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice' }),
});
const data = await res.json();

Tired of looking up syntax?

DocuWriter.ai generates documentation and explains code using AI.

Try Free

Modules

3 snippets

CommonJS and ESM

CommonJS

// export
module.exports = { myFunc, MyClass };
module.exports = function() {};
// import
const { myFunc } = require('./myModule');

ES Modules

// export
export function myFunc() {}
export default class MyClass {}
// import
import { myFunc } from './myModule.js';
import MyClass from './myModule.js';

package.json type

// CommonJS (default)
{ "type": "commonjs" }
// ESM
{ "type": "module" }

Process & Environment

4 snippets

Process management and env vars

Environment

const port = process.env.PORT || 3000;
const isProd = process.env.NODE_ENV === 'production';

CLI Arguments

const args = process.argv.slice(2);
// node script.js --port 3000
// args = ['--port', '3000']

Child Process

const { execSync, spawn } = require('child_process');
const output = execSync('ls -la').toString();
const child = spawn('node', ['worker.js']);

Exit & Signals

process.on('SIGTERM', () => {
  server.close(() => process.exit(0));
});
process.on('uncaughtException', (err) => {
  console.error(err);
  process.exit(1);
});

Buffers & Crypto

3 snippets

Binary data and hashing

Buffers

const buf = Buffer.from('Hello', 'utf8');
const hex = buf.toString('hex');
const b64 = buf.toString('base64');
const combined = Buffer.concat([buf1, buf2]);

Crypto Hash

const crypto = require('crypto');
const hash = crypto.createHash('sha256')
  .update('data').digest('hex');

Random

const token = crypto.randomBytes(32).toString('hex');
const uuid = crypto.randomUUID();

More Cheat Sheets

FAQ

Frequently asked questions

What is a Node.js cheat sheet?

A Node.js cheat sheet is a quick reference guide containing the most commonly used syntax, functions, and patterns in Node.js. It helps developers quickly look up syntax without searching through documentation.

How do I learn Node.js quickly?

Start with the basics: variables, control flow, and functions. Use this cheat sheet as a reference while practicing. For faster learning, try DocuWriter.ai to automatically explain code and generate documentation as you learn.

What are the most important Node.js concepts?

Key Node.js concepts include variables and data types, control flow (if/else, loops), functions, error handling, and working with data structures like arrays and objects/dictionaries.

How can I document my Node.js code?

Use inline comments for complex logic, docstrings for functions and classes, and README files for projects. DocuWriter.ai can automatically generate professional documentation from your Node.js code using AI.

Related resources

Stop memorizing. Start shipping.

Generate Node.js Docs with AI

DocuWriter.ai automatically generates comments, docstrings, and README files for your code.

Auto-generate comments
Create README files
Explain complex code
API documentation
Start Free - No Credit Card

Join 33,700+ developers saving hours every week