Sub topic 5
Node.js Built-in Modules: fs, path, process, and http
The browser hands you document and fetch. Node.js hands you modules that reach the file system, the operating system process, and the network. This chapter covers the four you will use most often. fs reads and writes files, path builds file paths safely, process describes the running program, and http serves web requests.
This chapter assumes you can run a script with node, that you know import syntax, and that you are comfortable with async/await. All examples are ES modules saved as .mjs files and need Node.js 18 or later.
Importing built-ins with the `node:` prefix
Built-in modules ship with Node.js itself, so npm install is never needed for them. Import them with the node: prefix:
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import process from 'node:process';The prefix is optional for older modules such as fs. It is still worth using for two reasons. The prefix tells a reader the module is built in. It also guarantees that an npm package with the same name, such as a package called path in node_modules, cannot be loaded in its place. Some newer modules, such as node:test, can only be loaded with the prefix.
fs: the file system
The fs module offers almost every operation in three styles. They share names and behavior and differ only in how they deliver results.
| Style | Import | Example | Blocks the event loop? |
|---|---|---|---|
| Promise | `node:fs/promises` | `await readFile(p, 'utf8')` | No |
| Callback | `node:fs` | `readFile(p, 'utf8', (err, data) => {})` | No |
| Synchronous | `node:fs` | `readFileSync(p, 'utf8')` | Yes |
Use the promise style by default. The synchronous style is fine in short command-line scripts and during startup, for example when you read a config file once before a server starts listening. Inside a request handler it is a mistake, because each call freezes every other request until the disk responds. The callback style exists mainly for older code.
Reading, writing, and listing
// files.mjs
import { mkdir, writeFile, readFile, readdir, stat } from 'node:fs/promises';
await mkdir('out/logs', { recursive: true }); // no error if it exists
await writeFile('out/logs/a.txt', 'first line\n'); // creates or overwrites
await writeFile('out/logs/a.txt', 'second line\n', { flag: 'a' }); // append
const text = await readFile('out/logs/a.txt', 'utf8');
console.log(text);
for (const entry of await readdir('out', { withFileTypes: true })) {
console.log(entry.name, entry.isDirectory() ? 'dir' : 'file');
}
const info = await stat('out/logs/a.txt');
console.log(info.size, 'bytes, modified', info.mtime.toISOString());Two details catch people. If you leave out the encoding argument, readFile returns a Buffer, which holds raw bytes, and printing it shows <Buffer 66 69 ...> instead of text. Pass 'utf8' when you want a string. The other detail is that writeFile replaces the whole file unless you pass { flag: 'a' } or call appendFile.
Handling errors by code
Failed file operations reject with an Error that carries a string code. Check the code to decide what to do:
// config.mjs
import { readFile } from 'node:fs/promises';
async function loadConfig(file) {
try {
return JSON.parse(await readFile(file, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return {}; // missing file: use defaults
throw err; // anything else is a real problem
}
}
console.log(await loadConfig('config.json'));| Code | Meaning |
|---|---|
| `ENOENT` | No such file or directory |
| `EACCES` | Permission denied |
| `EEXIST` | File already exists, for example with flag `'wx'` |
| `EISDIR` | Expected a file but found a directory |
| `ENOTDIR` | A part of the path is not a directory |
Large files
readFile loads the entire file into memory. For files of hundreds of megabytes, use a stream, which processes the data in chunks:
// count-lines.mjs
import { createReadStream } from 'node:fs';
import { createInterface } from 'node:readline';
const rl = createInterface({ input: createReadStream(process.argv[2]) });
let lines = 0;
for await (const _line of rl) lines++;
console.log(lines);path: building paths correctly
Separators differ between systems: Windows uses \ and POSIX systems use /. Joining paths with string concatenation also produces doubled or missing slashes. The path module handles both problems.
// paths.mjs
import path from 'node:path';
console.log(path.join('data', 'raw', '../clean', 'a.csv')); // data/clean/a.csv
console.log(path.resolve('data', 'a.csv')); // absolute, based on process.cwd()
console.log(path.basename('/tmp/report.pdf')); // report.pdf
console.log(path.extname('archive.tar.gz')); // .gz
console.log(path.dirname('/tmp/x/report.pdf')); // /tmp/x
console.log(path.parse('/tmp/report.pdf'));
// { root: '/', dir: '/tmp', base: 'report.pdf', ext: '.pdf', name: 'report' }People often mix up join and resolve. path.join glues segments together and normalizes the result, and it returns a relative path when you start from a relative one. path.resolve always returns an absolute path. It works right to left until it has an absolute path, and if it never finds one it prepends the current working directory. It also treats an absolute segment as a restart point, so path.resolve('/a', '/b') returns /b, while path.join('/a', '/b') returns /a/b.
Relative to what?
A relative path given to fs is resolved against process.cwd(), the directory the user ran node from. It is not resolved against the script's location. If node tools/build.mjs reads 'template.html', Node.js looks in the current directory, not in tools/.
To find files that sit next to the module, build the path from the module's own location. CommonJS provides __dirname for this. ES modules do not, so you derive it from import.meta.url:
// locate.mjs
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
console.log('module dir:', here);
console.log('cwd: ', process.cwd());
console.log('template: ', path.join(here, 'template.html'));Node.js 20.11 and later also provide import.meta.dirname directly. The fileURLToPath version works on every supported release.
process: the running program
process is available as a global, and it can also be imported from node:process. It describes the program that is currently running and lets you control it.
// proc.mjs
console.log(process.argv.slice(2)); // user arguments
console.log(process.env.HOME ?? process.env.USERPROFILE);
console.log(process.cwd(), process.pid, process.platform);
console.log(process.versions.node);
console.log(process.memoryUsage().heapUsed);Environment variables
process.env holds environment variables. Every value in it is a string or undefined. That means process.env.DEBUG = false stores the string 'false', which is truthy. Convert values explicitly when you read them:
const port = Number(process.env.PORT ?? 3000);
const verbose = process.env.VERBOSE === '1';Node.js 20.6 and later can load a file of variables with node --env-file=.env app.mjs, so a small project does not need an extra package for this.
Exiting cleanly
A Node.js program exits on its own once nothing is left to do: no pending timers, open sockets, or unfinished I/O. To report failure, set process.exitCode and let the program finish:
if (process.argv.length < 3) {
console.error('usage: node tool.mjs <file>');
process.exitCode = 1;
}process.exit(1) stops the process immediately. When standard output is a pipe, writes that have not been flushed yet can be lost, and pending async work is dropped. Call process.exit only when you really need to stop at once.
Your code can also respond to signals. SIGINT is the signal Ctrl+C sends:
process.on('SIGINT', () => {
console.log('shutting down');
process.exitCode = 0;
// close servers and database connections here
});Once you add a SIGINT listener, Ctrl+C no longer kills the process by itself. Your handler has to close whatever is keeping the program alive.
http: a server with no framework
Frameworks such as Express are built on the http module. You call createServer with a function, and Node.js calls that function once for each request with two objects. req is an IncomingMessage holding the method, URL, and headers. res is a ServerResponse that you write the reply to.
The server below uses all four modules together. It serves static files from a public folder:
// server.mjs (create public/index.html first, then run: node server.mjs)
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
const publicDir = path.join(here, 'public');
const port = Number(process.env.PORT ?? 3000);
const types = {
'.html': 'text/html; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.json': 'application/json',
};
const server = createServer(async (req, res) => {
try {
const { pathname } = new URL(req.url, 'http://localhost');
const wanted = pathname === '/' ? '/index.html' : decodeURIComponent(pathname);
const filePath = path.join(publicDir, wanted);
// Refuse paths like /../server.mjs that escape publicDir.
if (!filePath.startsWith(publicDir + path.sep)) {
res.writeHead(403, { 'Content-Type': 'text/plain' });
res.end('Forbidden');
return;
}
const body = await readFile(filePath);
res.writeHead(200, {
'Content-Type': types[path.extname(filePath)] ?? 'application/octet-stream',
});
res.end(body);
} catch (err) {
const status = err.code === 'ENOENT' ? 404 : 500;
res.writeHead(status, { 'Content-Type': 'text/plain' });
res.end(status === 404 ? 'Not found' : 'Server error');
}
});
server.listen(port, () => console.log(`Listening on http://localhost:${port}`));
process.on('SIGINT', () => {
server.close(() => console.log('server closed'));
server.closeAllConnections?.(); // drop idle keep-alive sockets (Node 18.2+)
});Common http mistakes
- Forgetting
res.end(). The browser keeps waiting until it times out. Every path through the handler must end the response, including error paths. - Writing headers twice. If you call
writeHeadafter the body has started, Node.js throwsERR_HTTP_HEADERS_SENT. This usually means two branches both responded, often because areturnis missing. - Trusting
req.url. The client controls the URL. Without thestartsWithcheck above, a request for/../server.mjswould expose your source code. This is called path traversal. - Unhandled rejections in the handler.
createServerdoes not await your async handler. If the handler throws without atry/catch, the request hangs, and depending on Node.js settings the whole process can crash. EADDRINUSEon listen. Another process is already using the port. Choose anotherPORTor stop the other process.
Exercise
A script at /home/ada/tools/report.mjs calls readFile('data.csv', 'utf8'). Ada runs it from /home/ada with node tools/report.mjs. Which file does Node.js try to open, and how should the script refer to a data.csv that sits next to report.mjs?
Show answer
Node.js opens /home/ada/data.csv, because relative paths are resolved against process.cwd(), not against the script's location. To use the file beside the script, build the path from the module's directory: path.join(path.dirname(fileURLToPath(import.meta.url)), 'data.csv'), or path.join(import.meta.dirname, 'data.csv') on Node.js 20.11 and later.
Exercise
What do path.join('/srv', '/app', 'x.js') and path.resolve('/srv', '/app', 'x.js') return on Linux, and why do they differ?
Show answer
path.join returns /srv/app/x.js, because it concatenates the segments and normalizes the result. path.resolve returns /app/x.js, because it treats the absolute segment '/app' as a new starting point and ignores everything before it.
Exercise
A CLI tool ends with console.log(bigReport); process.exit(0). When its output is piped to a file, the end of the report is sometimes missing. Why, and what is the fix?
Show answer
When stdout is a pipe, writes can be asynchronous, and process.exit ends the process before the buffered data is flushed. Remove the process.exit call, and set process.exitCode instead if you need a non-zero status. Node.js then exits on its own after the output has been written.