Handbooks / Node.js / Chapter 3
Core Modules: fs, path, http and os
7 pages · ~5 min✓ Reviewed
Builds on The Node.js Event Loop. Next up: Streams and Buffers.
Core Modules and the fs Mental Model
1. Core modules
- Core modules ship with Node: no install
- Import with the node: prefix to show they are built in
import fs from 'node:fs'
2. Three fs API styles
| Style | Call | Event loop | Errors |
|---|---|---|---|
| Callback | fs.readFile(path, cb) | free (thread pool) | cb(err, data) |
| Sync | fs.readFileSync | blocked until done | throws |
| Promise | fs/promises or fs.promises.readFile | free (thread pool) | rejects |
- Callback: err is always the first argument
- Sync: wrap in
try/catch
javascript
import fs from 'node:fs'; import { readFile } from 'node:fs/promises'; fs.readFile('a.txt', 'utf8', (err, data) => {}); const text = await readFile('a.txt', 'utf8'); try { fs.readFileSync('a.txt', 'utf8'); } catch (e) {}
callback, promise, sync
3. Buffer or string
fs Workflow: Promises, Callbacks and Sync Compared
1. Which Style
- Preferred: fs/promises +
awaitinside try/catch - Import:
import { readFile, writeFile } from 'node:fs/promises'
| Style | Suits |
|---|---|
| Callbacks |
path and __dirname in ES Modules
1. join vs resolve
joinconcatenates segments and normalizes separators and..- The result of
joincan stay relative resolvebuilds an absolute path, processing right to left until absolute- If no segment is absolute, it falls back to
process.cwd()
The http Module and a Minimal Server
1. Server, req and res
http.createServer(cb)returns a server; cb runs once per requestserver.listen(port)starts itreq: readable stream withreq.method,req.url,req.headersres: ==writable stream**
js
import { createServer } from 'node:http'; createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ ok: true })); }).listen(3000);
minimal JSON server
os, process, URL and querystring
1. os and process
os.cpus().lengthcores;os.totalmem()andos.freemem()in bytesos.platform()gives linux, win32 or darwinos.homedir(),os.tmpdir(),os.EOL(line ending)
| process |
|---|
Node Core Modules Cheat Sheet
1. fs and path
| Module | Remember |
|---|---|
| fs | promises for servers, Sync only at startup |
| fs | always pass 'utf8'; mkdir with recursive: true; rm with force: true |
| path | join concatenates; resolve gives an absolute path from cwd |
Check yourself
On Linux, what do path.join('/a', '/b') and path.resolve('/a', '/b') return?
joingives'/a/b': it only concatenates.resolvegives'/b': an absolute segment resets the path.
A file in a type: module project calls path.join(__dirname, 'data.json'). What happens, and what is the fix?
- ReferenceError:
__dirnameexists only in CommonJS.