Why this matters
You use Node.js when you want to build the server side of a web application in JavaScript. Instead of learning a second language for the back end, you write routes, talk to a database, and serve JSON using the same syntax you use in the browser. This makes it a natural choice for teams already comfortable with JavaScript.
Node is also the engine behind an enormous toolbox of developer tools. Build systems, test runners, bundlers, and command-line utilities are often written in Node and installed through npm. Even if you never run a Node server, you will probably use tools that depend on it.
Its event-driven design suits applications that handle many simultaneous connections, such as chat servers, APIs, and realtime dashboards. Node does not create a new thread for every request. Instead it uses asynchronous functions and an event loop to keep working while slow operations finish in the background.
The big picture
Think of a Node program as a set of functions waiting to be called. Some are called once at startup, some are called when a request arrives, and some are called when a file read or timer completes. The runtime keeps a queue of these callbacks and runs them one at a time on a single thread.
Because only one function runs at a time, you never get the usual threading bugs, but you also must never block. A function that spends a long time doing CPU-heavy work freezes everything else. The solution is to use asynchronous APIs that hand work off and call you back when it is done.
Modules are the organizing unit in Node. Each file is its own module with its own scope, and you share code by exporting functions from one file and requiring them in another. This keeps large programs from becoming one tangled global space.
Core ideas
What a runtime is
Node.js is not a language; it is a program that runs JavaScript. It takes the same engine that Chrome uses and adds things a browser does not provide, such as file system access, network servers, and a way to load modules from disk. The language stays the same; the environment grows.
This means the JavaScript you write in a browser and the JavaScript you write in Node look alike, but the available objects differ. In the browser you have document and window. In Node you have process and built-in modules such as fs and http. Knowing which environment you are in matters.
console.log(process.version);
console.log(process.argv);
Watch out. Do not expect browser globals like document or window to exist in Node. Code that touches the DOM will fail. Use modules such as fs and http for server-side work.
Modules and require
A module is a file that can expose selected values to other files. In CommonJS, the module system Node made famous, you put values on module.exports and load them with require. Each module has its own scope, so variables in one file do not leak into another.
Node also supports ES modules with export and import, which are increasingly common. You choose between them with the type field in package.json or a different file extension. Whichever style you use, the goal is the same: small files that do one job and declare what they need.
const math = require('./math.js');
console.log(math.add(2, 3));
// math.js: module.exports = { add: (a, b) => a + b };
Watch out. Require caches modules, so the code in a module runs only once. Do not put per-request state in module scope expecting it to reset. Use a function to create fresh state instead.
Callbacks
A callback is a function you pass to another function to be called later. Node uses them everywhere because many operations, such as reading a file, are slow. Instead of waiting, Node starts the operation and calls your function with the result when it is ready.
This is why Node code often has functions inside functions. The outer code sets work in motion, and the inner function handles the outcome. Callbacks keep the program responsive, but passing them through several layers makes code harder to read, a problem known as callback nesting.
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, text) => {
if (err) throw err;
console.log(text);
});
Watch out. Never assume a callback runs immediately, or even at all. Code written after the call may run first. Put everything that depends on the result inside the callback.
The event loop
The event loop is the mechanism that lets Node handle many tasks with one thread. When an asynchronous operation finishes, its callback is placed in a queue. The event loop picks callbacks from that queue and runs them one by one, never interrupting a function partway through.
This design is efficient for input and output work, because waiting happens outside your thread. It is less suitable for heavy computation, which blocks every other callback. Timers, network requests, and file reads all feed the same queue, so a slow callback delays everything behind it.
setTimeout(() => console.log('later'), 0);
console.log('now');
// prints: now, then later
Watch out. A zero millisecond timer does not run immediately. It is queued and runs only after the current code finishes. If order matters, write the code directly instead of relying on setTimeout.
Promises
A promise is an object representing a result that will exist later. It starts as pending and ends as either fulfilled with a value or rejected with a reason. You attach handlers with then and catch, which keeps success and failure paths explicit without passing callbacks through layers.
Promises also chain. Because then returns a new promise, you can write a sequence of steps where each one receives the previous result. This flat chain is much easier to follow than deeply nested callbacks and makes error handling straightforward with a single catch at the end.
const fs = require('fs/promises');
fs.readFile('data.txt', 'utf8')
.then(text => console.log(text))
.catch(err => console.error(err));
Watch out. A common bug is forgetting to return a promise from inside then. Without return, the chain continues before the inner work finishes, and errors inside it escape the final catch.
async and await
An async function is a function that always returns a promise. Inside it, the await keyword pauses execution until a promise settles, then continues with the resolved value. To the reader, asynchronous code starts to look like ordinary sequential code, which is far easier to reason about.
Because await pauses rather than blocks, the event loop stays free to run other callbacks. Errors from awaited calls can be caught with try and catch, so you handle failures in the same style you use everywhere else. Most modern Node code prefers async and await over raw promise chains.
const fs = require('fs/promises');
async function show() {
const text = await fs.readFile('data.txt', 'utf8');
console.log(text);
}
show().catch(console.error);
Watch out. You can only use await inside an async function, except at the top level of an ES module. Calling an async function without awaiting or catching its promise can leave errors unhandled.
Error-first callbacks
Older Node APIs follow a convention where the callback's first argument is an error and the second is the result. On success the error is null; on failure the result is usually undefined. You see this shape in fs, net, and many older packages, so you must recognize it.
Always check the error before using the result. Passing an error along to the next callback, often called propagating it, keeps your own functions consistent with the rest of Node. Modern promise-based APIs throw instead, which is why mixing the two styles needs care.
fs.readFile('x.txt', 'utf8', (err, data) => {
if (err) return console.error(err);
console.log(data);
});
Watch out. Do not ignore the error argument or assume it is always null. Wrapping the rest of the callback in an early return after checking err keeps the happy path clear.
HTTP request handlers
A Node server is mostly a function that receives a request and sends a response. The built-in http module calls your handler for each incoming request, giving you a request object and a response object. You read the URL and method from the first, and write status, headers, and body to the second.
Frameworks such as Express wrap this idea in routes, but the underlying concept is identical: a function mapped to a path and method. Handlers are called by the runtime, so they must be asynchronous and must eventually end the response, or the connection will hang.
const http = require('http');
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello from Node');
}).listen(3000);
Watch out. Forgetting to call res.end leaves the browser waiting forever. Every branch of your handler must finish the response, including error paths.
Functions
In Node, functions are not just a way to group statements; they are the units of scheduling. The runtime calls your functions at specific moments, such as when a request arrives or when a file finishes loading. Learning to think in terms of which function runs when is the heart of Node programming.
This section connects the forms you already know to the way Node actually works. You will see how callbacks feed the event loop, how modules export functions, how promises and async functions are just newer function shapes, and how to keep deeply nested callbacks from taking over your code.
Callbacks and the event loop
When you start an asynchronous operation, you hand Node a function to run when it finishes. That function goes into a queue. The event loop takes one queued callback at a time and runs it to completion before taking the next, which is why your code never has to lock two threads around the same data.
The practical consequence is that callbacks define the order of your program. Work that must happen after a file read belongs inside the read callback, not after the call in the source file. Understanding this prevents a large class of race bugs.
const fs = require('fs');
fs.readFile('a.txt', 'utf8', () => {
console.log('file done');
});
console.log('setup done');
Module functions and exports
Node treats each file as a module, and the cleanest way to share code is to export functions. A single file can export several named functions, and another file imports exactly the ones it needs. This keeps the public surface small and makes dependencies easy to see.
Because each module has its own scope, a helper function that is not exported stays private. That is a simple but powerful way to hide details. When a module grows too large, split it into smaller modules that each expose a few focused functions.
const { add, multiply } = require('./math.js');
console.log(add(2, 3), multiply(2, 3));
Error-first callbacks
The error-first convention gives every callback the same shape: an error argument first, then the result. Your job is to check that first argument before doing anything else. If it contains a value, something failed, and the result should be ignored.
When you write your own asynchronous function, follow the same convention so callers already know how to use it. Returning early after reporting an error keeps the rest of the function focused on the successful path and avoids nesting an else around everything.
function read(fn) {
fs.readFile('x.txt', 'utf8', (err, text) => {
if (err) return fn(err);
fn(null, text.toUpperCase());
});
}
Promises as function results
A promise-returning function represents work that will finish later. Instead of accepting a callback, it gives you an object you can attach handlers to. That flips the direction of control: the caller decides what happens next by chaining then calls rather than passing code inward.
Because then returns another promise, steps line up in a readable chain. A single catch at the end handles failures from any earlier step, which is much simpler than checking an error argument at every level.
const fs = require('fs/promises');
function upper(path) {
return fs.readFile(path, 'utf8').then(t => t.toUpperCase());
}
upper('x.txt').then(console.log);
async and await
Marking a function async means it always returns a promise, even if the body returns a plain value. Inside it, await waits for a promise and hands you the resolved value. The code reads top to bottom, yet the event loop remains free while the wait happens.
Use try and catch around await to handle failures, just as you would with synchronous code. Since an async function returns a promise, the code that calls it must either await it or attach a catch, or a rejected promise may go unhandled.
async function total(path) {
try {
const text = await fs.readFile(path, 'utf8');
return text.length;
} catch (err) {
return 0;
}
}
Request handlers as functions
A web server in Node is a function that maps an incoming request to an outgoing response. The http module supplies the request and response objects, and your handler reads the method and URL, then writes a status code and body. Every handler must finish the response.
Frameworks add routing and convenience helpers, but they do not change this model. Once you see handlers as ordinary functions called by the runtime, middleware and route handlers stop feeling mysterious.
const http = require('http');
const handler = (req, res) => {
res.writeHead(200);
res.end(req.url);
};
http.createServer(handler).listen(3000);
Avoiding callback nesting
When one asynchronous operation depends on another, naive callback code nests a function inside a function inside a function. The result is often called callback hell: indentation grows, error handling repeats, and the logic becomes hard to follow.
You can flatten it in two ways. Promises and async functions turn the sequence into a chain or straight-line code. Named functions also help, because giving each step a name lets you pass it around instead of inlining it. Prefer whichever keeps the flow obvious.
async function run() {
const a = await fs.readFile('a.txt', 'utf8');
const b = await fs.readFile('b.txt', 'utf8');
return a + b;
}
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
require/import
Module form
require loads a CommonJS module, while import loads an ES module. You use them to bring in code from other files and from installed packages so you can build programs from small pieces.
| Syntax | const fs = require("fs"); or import fs from "fs"; |
|---|---|
| Parameters | specifier — The module name or relative path to load |
| Returns | The module's exported value. |
// CommonJS
const path = require("path");
console.log(path.join("a", "b"));
// ES modules
import fs from "fs";
console.log(typeof fs.readFileSync);
What you can do with it. Load built-in modules like fs and path Bring in functions from your own files Use installed packages from node_modules
Choose it when. Choose import for modern ES modules and require for CommonJS code or older projects.
| Mistake | Fix |
|---|---|
| Mixing require and import without setup | Pick one module system, or set type in package.json for ES modules |
| Forgetting ./ for local files | Use a relative path like ./utils for your own modules |
module.exports
Module form
module.exports publishes values from a CommonJS file so other files can require them. You use it to share functions and data between modules instead of duplicating code.
| Syntax | module.exports = value; |
|---|---|
| Parameters | value — The object, function, or value to export |
| Returns | Nothing directly; it sets what require returns. |
// math.js
module.exports = {
add: (a, b) => a + b
};
// main.js
const math = require("./math");
console.log(math.add(2, 3));
What you can do with it. Share helper functions across files Export a single class or object Organize code into reusable modules
Choose it when. Choose module.exports in CommonJS projects rather than export default in ES modules.
| Mistake | Fix |
|---|---|
| Reassigning exports instead of module.exports | Set module.exports or add properties to exports, not both arbitrarily |
| Forgetting to require the file to use its exports | Call require("./file") in the consuming module |
callback
Async form
A callback is a function passed to an asynchronous API and called when the work finishes. Node uses this pattern heavily for file and timer operations, so you meet it early.
| Syntax | fs.readFile(path, (err, data) => { ... }); |
|---|---|
| Parameters | err — An error object if the operation failed, otherwise null data — The result passed on success |
| Returns | Callbacks return nothing to the API; results arrive through their arguments. |
const fs = require("fs");
fs.readFile("data.txt", "utf8", (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
What you can do with it. Handle file reads without blocking Respond to timer completion Chain steps after an async operation
Choose it when. Choose a callback for older Node APIs that expect one rather than forcing promises.
| Mistake | Fix |
|---|---|
| Ignoring the error argument | Check err first and handle it before using the data |
| Nesting many callbacks deeply | Use promises or async/await to flatten the flow |
EventEmitter.on
Method form
EventEmitter.on registers a listener that runs every time a named event is emitted. You use it to react to events in an event-driven program without tightly coupling the parts.
| Syntax | emitter.on(eventName, listener) |
|---|---|
| Parameters | eventName — The name of the event to listen for listener — The function called when the event fires |
| Returns | The emitter itself, so calls can be chained. |
const EventEmitter = require("events");
const bus = new EventEmitter();
bus.on("message", text => {
console.log("got:", text);
});
bus.emit("message", "hello");
What you can do with it. Build custom event-driven components Listen for data or error events on streams Decouple producers from consumers
Choose it when. Choose EventEmitter.on when you want a listener that fires on every event rather than just once.
| Mistake | Fix |
|---|---|
| Using once when you want repeated events | Use on for every occurrence and once for a single occurrence |
| Forgetting to remove listeners you no longer need | Call emitter.off or removeListener to avoid leaks |
http.createServer
Server function
http.createServer builds a web server that calls a handler for each incoming request. You use it to serve pages or build a small API using only Node's built-in modules.
| Syntax | http.createServer((req, res) => { ... }).listen(port) |
|---|---|
| Parameters | request — The incoming request object response — The object used to send the reply |
| Returns | An http.Server instance you can start listening with. |
const http = require("http");
const server = http.createServer((req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello from Node");
});
server.listen(3000, () => console.log("ready"));
What you can do with it. Serve a simple webpage locally Build a small JSON API Handle requests during local testing
Choose it when. Choose http.createServer for a lightweight local server rather than pulling in a full framework.
| Mistake | Fix |
|---|---|
| Forgetting to call res.end() | Always end the response or the client hangs |
| Listening on a port already in use | Choose a different port or stop the process occupying it |
fs.readFile
File system function
fs.readFile reads a whole file from disk into memory. You use the asynchronous form to load file contents without blocking the event loop while other work continues.
| Syntax | fs.readFile(path, options, callback) |
|---|---|
| Parameters | path — The file path to read options — Encoding such as utf8; optional callback — Function receiving (err, data) |
| Returns | Nothing directly; data is delivered to the callback. |
const fs = require("fs");
fs.readFile("notes.txt", "utf8", (err, data) => {
if (err) throw err;
console.log(data.toUpperCase());
});
What you can do with it. Load configuration or text files Read templates for a local server Inspect file contents during a script
Choose it when. Choose fs.readFile for async whole-file reads rather than streaming very large files.
| Mistake | Fix |
|---|---|
| Treating data as a string without an encoding | Pass "utf8" or convert the Buffer with toString() |
| Using blocking readFileSync in server code | Prefer the async form so other requests are not blocked |
path.join
Path function
path.join combines path segments into one correctly formatted path. You use it to build file paths that work across operating systems instead of guessing separators.
| Syntax | path.join(...segments) |
|---|---|
| Parameters | segments — Path parts to join with the correct separator |
| Returns | A single normalized path string. |
const path = require("path");
const file = path.join(__dirname, "data", "notes.txt");
console.log(file);
console.log(path.join("a", "..", "b"));
What you can do with it. Build portable file paths Locate files relative to the current module Normalize paths with dot segments
Choose it when. Choose path.join when combining path pieces rather than concatenating strings with a slash.
| Mistake | Fix |
|---|---|
| Hardcoding slashes in paths | Use path.join so Windows and Unix separators are handled |
| Forgetting __dirname for file locations | Join from __dirname for paths relative to your source file |
setTimeout
Timer function
setTimeout runs a function once after a delay in milliseconds. You use it to schedule work for later without blocking the event loop.
| Syntax | setTimeout(callback, delay, ...args) |
|---|---|
| Parameters | callback — Function to run after the delay delay — Milliseconds to wait args — Extra arguments passed to the callback |
| Returns | A timer object you can pass to clearTimeout to cancel it. |
const id = setTimeout(() => {
console.log("runs after 1 second");
}, 1000);
// clearTimeout(id) cancels it before it runs
What you can do with it. Delay a task by a short interval Debounce repeated events Retry an operation after a pause
Choose it when. Choose setTimeout for a one-time delay rather than setInterval for repeating work.
| Mistake | Fix |
|---|---|
| Assuming the delay is exact | Treat it as a minimum; the callback runs after at least that time |
| Forgetting how to cancel a scheduled task | Keep the timer id and call clearTimeout when needed |
Promise
Async form
A Promise represents a value that will be available later. You use it to model asynchronous work with explicit success and failure outcomes that you can chain.
| Syntax | new Promise((resolve, reject) => { ... }) |
|---|---|
| Parameters | resolve — Call with a value to fulfill the promise reject — Call with a reason to reject the promise |
| Returns | A promise you can chain with .then and .catch. |
const wait = ms => new Promise(resolve => {
setTimeout(resolve, ms);
});
wait(500).then(() => console.log("done"));
const failed = Promise.reject(new Error("nope"));
failed.catch(err => console.error(err.message));
What you can do with it. Wrap callback-based APIs in a promise Coordinate delayed local operations Chain dependent async steps with then
Choose it when. Choose a Promise when you need a chainable result for work that completes later.
| Mistake | Fix |
|---|---|
| Forgetting to call resolve or reject | Always settle the promise, or callers wait forever |
| Nesting promises inside then | Return the inner promise so the chain flattens |
async/await
Async form
async marks a function as promise-based and await pauses inside it until a promise settles. You use them to write asynchronous code that reads in order from top to bottom.
| Syntax | async function name() { const value = await promise; } |
|---|---|
| Parameters | promise — A value returned by an asynchronous call |
| Returns | An async function always returns a promise. |
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
async function run() {
console.log("start");
await wait(300);
console.log("after pause");
return "finished";
}
run().then(result => console.log(result));
What you can do with it. Sequence several delayed local steps Read async code top to bottom Handle errors with try/catch around await
Choose it when. Choose async/await when you have dependent async steps rather than long .then chains.
| Mistake | Fix |
|---|---|
| Forgetting await on a promise | Add await so you get the resolved value instead of the promise |
| Using await in a non-async function | Mark the containing function async first |
process.env
Runtime object
process.env holds environment variables as strings. You use it to read configuration like ports or modes without hardcoding values into your source code.
| Syntax | process.env.VARIABLE_NAME |
|---|---|
| Parameters | VARIABLE_NAME — The name of the environment variable to read |
| Returns | A string value, or undefined if the variable is not set. |
const port = process.env.PORT || 3000;
console.log("listening on", port);
if (process.env.NODE_ENV === "production") {
console.log("live mode");
}
What you can do with it. Read a port from the environment Toggle debug or production behavior Keep secrets out of source code
Choose it when. Choose process.env for configuration that changes between environments rather than editing code.
| Mistake | Fix |
|---|---|
| Assuming values are numbers | Environment values are strings; convert with Number() or parseInt() |
| Assuming a variable is always set | Provide a fallback with || for missing values |
Buffer.from
Buffer function
Buffer.from creates a Buffer from a string or array of bytes. You use it when you need to handle raw binary data in Node, such as encoding or byte-level work.
| Syntax | Buffer.from(data, encoding) |
|---|---|
| Parameters | data — A string, array, or another buffer encoding — String encoding such as utf8; optional |
| Returns | A new Buffer holding the encoded bytes. |
const buf = Buffer.from("hello", "utf8");
console.log(buf.length);
console.log(buf.toString("hex"));
const bytes = Buffer.from([72, 105]);
console.log(bytes.toString());
What you can do with it. Convert text to bytes for binary operations Encode data as hex or base64 Build byte arrays for low-level tasks
Choose it when. Choose Buffer.from when you need byte-level data rather than ordinary JavaScript strings.
| Mistake | Fix |
|---|---|
| Treating a Buffer as a normal string | Call toString() to read it as text |
| Using the deprecated new Buffer() constructor | Use Buffer.from() instead |
JSON.parse
Parse function
JSON.parse converts JSON text into a JavaScript value. You use it in Node to read config files or request bodies that arrive as strings and need to become objects.
| Syntax | JSON.parse(text, reviver) |
|---|---|
| Parameters | text — The JSON string to convert reviver — Optional function to transform parsed values |
| Returns | The value described by the JSON text. |
const fs = require("fs");
const text = fs.readFileSync("config.json", "utf8");
const config = JSON.parse(text);
console.log(config.name);
console.log(JSON.parse("[1,2,3]").length);
What you can do with it. Load JSON configuration files Parse a JSON request body Rebuild data stored as JSON text
Choose it when. Choose JSON.parse when you have JSON as raw text rather than a ready object.
| Mistake | Fix |
|---|---|
| Parsing a value that is already an object | Only parse strings; skip parsing if the data is already parsed |
| Letting bad JSON crash the process uncaught | Wrap JSON.parse in try/catch and handle the error |
stream.pipe
Stream function
pipe sends the output of a readable stream into a writable stream. You use it to move data efficiently without loading everything into memory at once.
| Syntax | readable.pipe(writable) |
|---|---|
| Parameters | writable — The destination stream that receives the data |
| Returns | The destination stream, allowing further chaining. |
const fs = require("fs");
const read = fs.createReadStream("input.txt");
const write = fs.createWriteStream("output.txt");
read.pipe(write);
write.on("finish", () => console.log("copied"));
What you can do with it. Copy files without buffering them whole Transform data through a pipeline Forward request data to a response
Choose it when. Choose stream.pipe for large or continuous data rather than reading it all at once.
| Mistake | Fix |
|---|---|
| Forgetting to handle errors on the streams | Attach error listeners to both streams |
| Assuming pipe reports completion by itself | Listen for the finish event on the writable stream |
Common mistakes here
| Mistake | Fix |
|---|---|
| Writing code after an async call and expecting the result to be ready. | Put dependent code inside the callback or on the next line after an await. |
| Ignoring the error argument of an error-first callback. | Check err first and return early before touching the result. |
| Forgetting to return a promise from inside a then handler. | Return it so the chain waits and errors reach the final catch. |
| Calling an async function without handling the promise it returns. | Use await or attach a catch so failures are not silently swallowed. |
| Forgetting res.end in a request handler. | End the response on every path, including error paths. |
The example, line by line
This script loads users from a JSON file, extracts their names, and reports any failure, all through small async functions.
| Code | What it does |
|---|---|
1const fs = require('fs/promises'); | Import the promise-based version of the file system module. |
2async function loadUsers() { | Define an async function whose job is to load and parse the data. |
3 const text = await fs.readFile('users.json', 'utf8'); | Wait for the file contents as text before continuing. |
4 return JSON.parse(text); | Turn that text into JavaScript values and return them to the caller. |
5} | Close the loading function. |
6async function main() { | Define the main async function that coordinates the work. |
7 const users = await loadUsers(); | Wait for loadUsers to finish, then store the resulting array. |
8 const names = users.map(user => user.name); | Map each user object to just its name using an arrow callback. |
9 console.log('Users:', names.join(', ')); | Print the names joined into one comma separated line. |
10} | Close the main function. |
11main().catch(err => { | Call main and attach a catch for any rejected promise. |
12 console.error('Failed:', err.message); | Log a short failure message using the error's message property. |
13 process.exitCode = 1; | Set the process exit code to one so scripts can detect the failure. |
14}); | Close the catch callback and finish the statement. |
const fs = require('fs/promises');
async function loadUsers() {
const text = await fs.readFile('users.json', 'utf8');
return JSON.parse(text);
}
async function main() {
const users = await loadUsers();
const names = users.map(user => user.name);
console.log('Users:', names.join(', '));
}
main().catch(err => {
console.error('Failed:', err.message);
process.exitCode = 1;
});
Worked variations
An Express-style route
In a framework, a route is a function that handles one path and method. Express passes request and response objects to it, and your handler decides what to send back. The pattern is the same as a raw Node handler with less boilerplate.
Keeping route functions small makes them easy to test. Move the real work into separate functions and let the route focus on reading input and sending a response.
app.get('/users/:id', async (req, res) => {
const user = await findUser(req.params.id);
if (!user) return res.status(404).send('Not found');
res.json(user);
});
Reading config from JSON
A command-line tool often reads settings from a JSON file at startup. Parse it once, check the values you depend on, and keep the result in a constant. That avoids reading the file repeatedly during execution.
Because reading is asynchronous, do this inside an async main function before starting the rest of the program. Any parse error should produce a clear message and stop startup.
const raw = await fs.readFile('config.json', 'utf8');
const config = JSON.parse(raw);
if (!config.port) throw new Error('Missing port');
Common mistakes
| Mistake | Fix |
|---|---|
| Doing heavy synchronous computation inside a request handler. | Move CPU-heavy work to a worker or another process so the event loop stays free. |
| Assuming module scope resets between requests. | Keep per-request state inside the handler or a function that creates fresh state. |
| Mixing callback-style fs with promise-style fs in one chain. | Choose one style per feature and use the fs/promises module consistently. |
| Leaving a rejected promise unhandled after calling an async function. | Await it or attach a catch at the call site. |
| Hard-coding file paths that assume the current folder is fixed. | Resolve paths against __dirname or the project root so the script works from anywhere. |
Practice
- Write a small module that exports a function to format a date, then import it from another file.
- Use fs.readFile with a callback to count the lines in a file, handling errors correctly.
- Rewrite a nested callback chain as an async function with await and try and catch.
- Build an http server that returns JSON for one route and ends every response, including errors.