Node.js Snippets
About Node.js
Node.js lets you run JavaScript on the server and in automation scripts. This path covers core runtime features, file-based data, testing, and a mini project flow.
Project Structure for a Node Learning Workspace
Keep runtime code and command-line scripts separate so examples scale into real tools.
node-lab/
src/
server.js
routes.js
repo/taskRepo.js
worker/reminderWorker.js
scripts/
task-cli.js
data/
tasks.json
tests/
routes.test.js
package.jsonInitialize Project and Helpful Scripts
Set modern defaults and scripts for development and tests.
npm init -y
npm pkg set type=module
npm pkg set scripts.dev="node --watch src/server.js"
npm pkg set scripts.start="node src/server.js"
npm pkg set scripts.test="node --test"Build a JSON API with node:http (src/server.js)
Start with the built-in http module to understand fundamentals before frameworks.
import http from 'node:http'
import { handleRequest } from './routes.js'
const server = http.createServer(async (req, res) => {
try {
await handleRequest(req, res)
} catch (error) {
res.writeHead(500, { "content-type": "application/json" })
res.end(JSON.stringify({ message: error.message }))
}
})
server.listen(3000, () => {
console.log('Server running on http://localhost:3000')
})File-Based Repository (src/repo/taskRepo.js)
Use fs/promises to keep persistence simple for learning projects.
import { readFile, writeFile } from 'node:fs/promises'
const DATA_FILE = new URL('../../data/tasks.json', import.meta.url)
export async function readTasks() {
const text = await readFile(DATA_FILE, "utf8")
return JSON.parse(text)
}
export async function saveTasks(tasks) {
await writeFile(DATA_FILE, JSON.stringify(tasks, null, 2))
}Simple Route Handler (src/routes.js)
Route manually to understand request parsing and response writing.
import { readTasks } from './repo/taskRepo.js'
export async function handleRequest(req, res) {
if (req.method === 'GET' && req.url === '/tasks') {
const tasks = await readTasks()
res.writeHead(200, { "content-type": "application/json" })
res.end(JSON.stringify(tasks))
return
}
res.writeHead(404, { "content-type": "application/json" })
res.end(JSON.stringify({ message: 'Not found' }))
}Mini Project: Task CLI Command Parser (scripts/task-cli.js)
Small project idea: maintain tasks from the terminal. Parse commands and reuse repo logic.
#!/usr/bin/env node
import { readTasks, saveTasks } from '../src/repo/taskRepo.js'
const [command, ...rest] = process.argv.slice(2)
const tasks = await readTasks()
if (command === 'add') {
const text = rest.join(' ').trim()
if (!text) throw new Error("Provide task text")
tasks.push({ id: crypto.randomUUID(), text, done: false })
await saveTasks(tasks)
console.log('Task added')
} else {
console.log('Usage: node scripts/task-cli.js add <text>')
}Mini Project: Reminder Worker (src/worker/reminderWorker.js)
Background loops are useful for automation, cron replacements, and polling jobs.
import { readTasks } from '../repo/taskRepo.js'
setInterval(async () => {
const tasks = await readTasks()
const pending = tasks.filter((task) => !task.done)
console.log('Pending tasks:', pending.length)
}, 60_000)Test a Route with node:test (tests/routes.test.js)
Use the built-in test runner for quick feedback without external tooling.
import test from 'node:test'
import assert from 'node:assert/strict'
test('sanity check', () => {
assert.equal(2 + 2, 4)
})Run Server, CLI, Worker, and Tests
Use these commands while practicing runtime, automation, and verification.
npm run dev
node scripts/task-cli.js add "Write docs"
node src/worker/reminderWorker.js
npm testNext Learning Upgrades
Use this list to evolve your Node snippets into production-quality patterns.
1. Add schema validation with zod before saving tasks.
2. Add structured logging and correlation IDs.
3. Move data from JSON file storage to PostgreSQL.
4. Add graceful shutdown for server and workers.
5. Add integration tests against real HTTP endpoints.