Sub topic 5
Node.js Built-in Modules: fs, path, process, and http
This chapter assumes you can run a script with the node command and know basic import syntax. Later chapters cover module systems and async patterns in more depth. This chapter covers the four built-in modules you will use most often.
Built-in modules ship with Node.js, so you don't install them with npm. Import them with the node: prefix, as in node:fs. The prefix makes it clear that the module is built in, and a package on disk with the same name can't shadow it.
| Module | Purpose | Browser equivalent |
|---|---|---|
| `fs` | Read and write files | None (sandboxed) |
| `path` | Build and parse file paths | None |
| `process` | Arguments, environment, exit codes | Partly `location`, `navigator` |
| `http` | Network servers and clients | `fetch` (client only) |
path: Building File Paths Safely
Windows separates folders with \ and POSIX systems use /. The path module handles that difference, so don't join path strings by hand.
// paths.mjs
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const here = path.dirname(fileURLToPath(import.meta.url));
console.log(path.join(here, 'data', 'notes.txt')); // OS-correct separators
console.log(path.resolve('notes.txt')); // absolute, from the current working directory
console.log(path.extname('report.final.pdf')); // '.pdf'
console.log(path.basename('/a/b/c.txt', '.txt')); // 'c'path.resolve works from the current working directory, which is the folder you ran node from. That folder is not necessarily where the script lives. Anchor paths to the script's own folder with import.meta.url instead.
fs: Working with Files
The fs module comes in three styles: callbacks (node:fs), synchronous calls (readFileSync), and promises (node:fs/promises). Use the promise style in new code.
// notes.mjs
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const dir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'out');
const file = path.join(dir, 'notes.txt');
await mkdir(dir, { recursive: true });
await writeFile(file, 'first line\n', 'utf8');
await writeFile(file, 'second line\n', { flag: 'a' }); // append
const text = await readFile(file, 'utf8');
console.log(text.split('\n').filter(Boolean)); // [ 'first line', 'second line' ]Synchronous calls such as readFileSync block the event loop. They are fine in startup scripts and CLI tools. Avoid them inside a server's request handlers, because every request waits while one handler blocks.
process: Talking to the Environment
process is a global, so you don't need to import it. It gives you arguments, environment variables, and control over the exit code.
// greet.mjs (run with: GREETING=Hi node greet.mjs Ada)
const [, , name] = process.argv;
const greeting = process.env.GREETING ?? 'Hello';
if (!name) {
console.error('Usage: node greet.mjs <name>');
process.exitCode = 1;
} else {
console.log(`${greeting}, ${name}!`);
console.log('cwd:', process.cwd(), 'platform:', process.platform);
}All environment variables are strings, so process.env.PORT is '3000' and not 3000. Setting process.exitCode is better than calling process.exit(). Node.js then exits after pending output and I/O finish, so nothing gets cut off.
http: A Minimal Server
The http module is low-level. Frameworks like Express are built on top of it.
// server.mjs
import http from 'node:http';
const port = Number(process.env.PORT ?? 3000);
const server = http.createServer((req, res) => {
if (req.method === 'GET' && req.url === '/health') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true, uptime: process.uptime() }));
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not found');
});
server.listen(port, () => console.log(`http://localhost:${port}/health`));Common Errors
- Forgetting
res.end(). If the handler never calls it, the client hangs until it times out. - Using relative paths in
fscalls. They resolve againstprocess.cwd(), so the script breaks when you run it from a different folder. - Using
__dirnamein an ES module. It isn't defined there. Useimport.meta.dirname(Node.js 20.11 and later) orfileURLToPath(import.meta.url). - Port already in use. A second
listenon the same port throwsEADDRINUSE. Stop the old process or changePORT.
Exercise
You run node tools/report.mjs from the project root, and the script calls readFile('data.json'). The file is at tools/data.json, but you get ENOENT. Why does this happen, and how do you fix it?
Show answer
Relative paths in fs resolve against process.cwd(), which is the project root here, so Node.js looks for ./data.json in the root. Build the path from the module's own location instead: path.join(path.dirname(fileURLToPath(import.meta.url)), 'data.json').
Exercise
In server.mjs, why is the port wrapped in Number(...), and what would res.end receive if you passed the object without JSON.stringify?
Show answer
Environment variables are always strings, so Number turns '3000' into a number. res.end accepts only a string, Buffer, or Uint8Array. Passing a plain object throws a TypeError, so you must serialize it with JSON.stringify first.