Node Examples
Useful Node patterns you reach for over and over - HTTP server, file streaming, child process, scheduled job, env-driven config.
Node by example
EXAMPLE
// 1. HTTP server, no framework
import { createServer } from 'http';
const server = createServer(async (req, res) => {
if (req.url === '/healthz') return res.end('ok');
if (req.url === '/json') {
res.writeHead(200, { 'content-type': 'application/json' });
return res.end(JSON.stringify({ ts: Date.now() }));
}
res.writeHead(404); res.end('not found');
});
server.listen(3000, () => console.log('listening'));
// 2. Stream big files - no slurping
import { createReadStream, createWriteStream } from 'fs';
import { pipeline } from 'stream/promises';
import { createGzip } from 'zlib';
await pipeline(
createReadStream('big.log'),
createGzip(),
createWriteStream('big.log.gz')
);
// 3. Spawn a child process - typed wrapper
import { spawn } from 'child_process';
function run(cmd: string, args: string[], opts = {}): Promise<{ stdout: string; stderr: string }> {
return new Promise((resolve, reject) => {
const p = spawn(cmd, args, opts);
let stdout = '', stderr = '';
p.stdout.on('data', (d) => stdout += d);
p.stderr.on('data', (d) => stderr += d);
p.on('close', (code) => code === 0 ? resolve({ stdout, stderr }) : reject(new Error(stderr)));
});
}
const { stdout } = await run('git', ['rev-parse', 'HEAD']);
// 4. Scheduled job with node-cron
import cron from 'node-cron';
cron.schedule('*/5 * * * *', async () => {
console.log('every 5 min', new Date().toISOString());
});
// 5. Env-driven config with zod
import { z } from 'zod';
const Env = z.object({
PORT: z.coerce.number().default(3000),
DATABASE_URL: z.string().url(),
NODE_ENV: z.enum(['development', 'production', 'test']).default('development'),
});
export const env = Env.parse(process.env);
// 6. Worker thread for CPU work
// worker.ts
import { parentPort } from 'worker_threads';
parentPort?.on('message', (n: number) => parentPort?.postMessage(fib(n)));
function fib(n: number): number { return n < 2 ? n : fib(n - 1) + fib(n - 2); }
// main.ts
import { Worker } from 'worker_threads';
const w = new Worker(new URL('./worker.ts', import.meta.url));
w.on('message', (r) => console.log(r));
w.postMessage(40);
// 7. Graceful shutdown
process.on('SIGTERM', async () => {
console.log('shutting down');
await server.close();
process.exit(0);
});
Why it matters
These are the seven patterns that show up in nearly every Node service. Streams for big data, child processes for shelling out, workers for CPU - the rest is event loop. Validate env at boot and shut down gracefully.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// Common Node snippets are in the lesson body.
console.log('Node examples');
Try it Yourself »
Discussion
Loading…