Async Patterns
4 snippetsCallbacks, 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 snippetsReading 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 snippetsBuilt-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.
Modules
3 snippetsCommonJS 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 snippetsProcess 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 snippetsBinary 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();