Vividly / Languages / Node.js

Node.js

Node.js is a runtime that lets you run JavaScript outside the browser, on servers and command-line tools, and it is for developers who want to use one language across an entire application.

Read the lesson →

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.

What a runtime isexample
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.

Modules and requireexample
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.

Callbacksexample
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.

The event loopexample
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.

Promisesexample
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.

async and awaitexample
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.

Error-first callbacksexample
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.

HTTP request handlersexample
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.

Callbacks and the event loopexample
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.

Module functions and exportsexample
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.

Error-first callbacksexample
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.

Promises as function resultsexample
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 and awaitexample
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.

Request handlers as functionsexample
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.

Avoiding callback nestingexample
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.

Syntaxconst fs = require("fs"); or import fs from "fs";
Parametersspecifier — The module name or relative path to load
ReturnsThe module's exported value.
require/importexample
// 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.

MistakeFix
Mixing require and import without setupPick one module system, or set type in package.json for ES modules
Forgetting ./ for local filesUse 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.

Syntaxmodule.exports = value;
Parametersvalue — The object, function, or value to export
ReturnsNothing directly; it sets what require returns.
module.exportsexample
// 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.

MistakeFix
Reassigning exports instead of module.exportsSet module.exports or add properties to exports, not both arbitrarily
Forgetting to require the file to use its exportsCall 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.

Syntaxfs.readFile(path, (err, data) => { ... });
Parameterserr — An error object if the operation failed, otherwise null
data — The result passed on success
ReturnsCallbacks return nothing to the API; results arrive through their arguments.
callbackexample
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.

MistakeFix
Ignoring the error argumentCheck err first and handle it before using the data
Nesting many callbacks deeplyUse 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.

Syntaxemitter.on(eventName, listener)
ParameterseventName — The name of the event to listen for
listener — The function called when the event fires
ReturnsThe emitter itself, so calls can be chained.
EventEmitter.onexample
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.

MistakeFix
Using once when you want repeated eventsUse on for every occurrence and once for a single occurrence
Forgetting to remove listeners you no longer needCall 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.

Syntaxhttp.createServer((req, res) => { ... }).listen(port)
Parametersrequest — The incoming request object
response — The object used to send the reply
ReturnsAn http.Server instance you can start listening with.
http.createServerexample
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.

MistakeFix
Forgetting to call res.end()Always end the response or the client hangs
Listening on a port already in useChoose 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.

Syntaxfs.readFile(path, options, callback)
Parameterspath — The file path to read
options — Encoding such as utf8; optional
callback — Function receiving (err, data)
ReturnsNothing directly; data is delivered to the callback.
fs.readFileexample
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.

MistakeFix
Treating data as a string without an encodingPass "utf8" or convert the Buffer with toString()
Using blocking readFileSync in server codePrefer 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.

Syntaxpath.join(...segments)
Parameterssegments — Path parts to join with the correct separator
ReturnsA single normalized path string.
path.joinexample
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.

MistakeFix
Hardcoding slashes in pathsUse path.join so Windows and Unix separators are handled
Forgetting __dirname for file locationsJoin 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.

SyntaxsetTimeout(callback, delay, ...args)
Parameterscallback — Function to run after the delay
delay — Milliseconds to wait
args — Extra arguments passed to the callback
ReturnsA timer object you can pass to clearTimeout to cancel it.
setTimeoutexample
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.

MistakeFix
Assuming the delay is exactTreat it as a minimum; the callback runs after at least that time
Forgetting how to cancel a scheduled taskKeep 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.

Syntaxnew Promise((resolve, reject) => { ... })
Parametersresolve — Call with a value to fulfill the promise
reject — Call with a reason to reject the promise
ReturnsA promise you can chain with .then and .catch.
Promiseexample
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.

MistakeFix
Forgetting to call resolve or rejectAlways settle the promise, or callers wait forever
Nesting promises inside thenReturn 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.

Syntaxasync function name() { const value = await promise; }
Parameterspromise — A value returned by an asynchronous call
ReturnsAn async function always returns a promise.
async/awaitexample
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.

MistakeFix
Forgetting await on a promiseAdd await so you get the resolved value instead of the promise
Using await in a non-async functionMark 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.

Syntaxprocess.env.VARIABLE_NAME
ParametersVARIABLE_NAME — The name of the environment variable to read
ReturnsA string value, or undefined if the variable is not set.
process.envexample
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.

MistakeFix
Assuming values are numbersEnvironment values are strings; convert with Number() or parseInt()
Assuming a variable is always setProvide 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.

SyntaxBuffer.from(data, encoding)
Parametersdata — A string, array, or another buffer
encoding — String encoding such as utf8; optional
ReturnsA new Buffer holding the encoded bytes.
Buffer.fromexample
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.

MistakeFix
Treating a Buffer as a normal stringCall toString() to read it as text
Using the deprecated new Buffer() constructorUse 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.

SyntaxJSON.parse(text, reviver)
Parameterstext — The JSON string to convert
reviver — Optional function to transform parsed values
ReturnsThe value described by the JSON text.
JSON.parseexample
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.

MistakeFix
Parsing a value that is already an objectOnly parse strings; skip parsing if the data is already parsed
Letting bad JSON crash the process uncaughtWrap 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.

Syntaxreadable.pipe(writable)
Parameterswritable — The destination stream that receives the data
ReturnsThe destination stream, allowing further chaining.
stream.pipeexample
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.

MistakeFix
Forgetting to handle errors on the streamsAttach error listeners to both streams
Assuming pipe reports completion by itselfListen for the finish event on the writable stream

Common mistakes here

MistakeFix
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.

CodeWhat 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.
Full examplecomplete
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.

An Express-style routevariation
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.

Reading config from JSONvariation
const raw = await fs.readFile('config.json', 'utf8');
const config = JSON.parse(raw);
if (!config.port) throw new Error('Missing port');

Common mistakes

MistakeFix
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

  1. Write a small module that exports a function to format a date, then import it from another file.
  2. Use fs.readFile with a callback to count the lines in a file, handling errors correctly.
  3. Rewrite a nested callback chain as an async function with await and try and catch.
  4. Build an http server that returns JSON for one route and ends every response, including errors.
Atmospheric photograph for this chapter Curved glass and steel lattice roof Stepped white modern building corner
Systems and connections. Follow one thread through to the end.

Where next