Sub topic 2
Node.js Built-in Modules: fs, path, process, and http
This chapter assumes you can run node file.mjs from a terminal and that you know basic promise syntax.
The Core Built-ins
Node.js ships with built-in modules. You import them with the node: prefix, which makes it clear they are not npm packages.
| Module | Purpose |
|---|---|
| `fs` | Read and write files |
| `path` | Join and resolve file paths across operating systems |
| `process` | Arguments, environment variables, exit codes |
| `http` | Create servers and make requests |
// server.mjs (run with: PORT=3000 node server.mjs)
import http from 'node:http';
import path from 'node:path';
import process from 'node:process';
const port = Number(process.env.PORT ?? 3000);
http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/plain');
res.end(`ext: ${path.extname(req.url) || 'none'}\n`);
}).listen(port, () => console.log(`Listening on ${port}`));ES Modules and CommonJS
Node.js supports two module systems. It picks one per file:
.mjsfiles are always ES modules (import/export)..cjsfiles are always CommonJS (require/module.exports)..jsfiles follow the nearestpackage.json:"type": "module"means ESM. Without that field, the file is treated as CommonJS.
The Event Loop
Node.js and the browser schedule work the same way. Synchronous code runs to completion first. Then the microtask queue (promise callbacks) is drained. Only after that do task callbacks such as timers run.
console.log('1: sync');
setTimeout(() => console.log('4: timer task'), 0);
Promise.resolve().then(() => console.log('3: microtask'));
console.log('2: sync');Asynchronous I/O with async/await
Blocking calls like fs.readFileSync stop the event loop. While one runs, a server can't answer any other request. Use the promise API instead. In an ES module you can await at the top level:
// read.mjs
import { readFile } from 'node:fs/promises';
try {
const text = await readFile(new URL('./data.txt', import.meta.url), 'utf8');
console.log(text.length);
} catch (err) {
console.error(`Could not read file: ${err.code}`);
}Passing new URL('./data.txt', import.meta.url) resolves the path relative to the module file, not the current working directory. A common bug is a relative path that only works when you launch the script from one particular folder.
Exercise
A file named app.js uses import statements and fails with "Cannot use import statement outside a module". Name two ways to fix it.
Show answer
Rename the file to app.mjs, or add "type": "module" to the nearest package.json.
Exercise
In what order do these log? setTimeout(() => console.log('a'), 0); queueMicrotask(() => console.log('b')); console.log('c');
Show answer
c, b, a. Synchronous code runs first, then microtasks, then the timer task.