What are the fs and path modules used for? Name a few functions of each, and explain why you should build file paths with path rather than string concatenation.
Show the explanation
Model answer.
`fs` (file system) reads and writes files and folders. It comes in three styles: callback (fs.readFile), promise (fs/promises → readFile), and synchronous (fs.readFileSync). Common functions:
readFile,writeFile,appendFilemkdir(with{ recursive: true }),readdir,stat,rmcreateReadStream,createWriteStreamfor large files
`path` works with file paths as strings, correctly for the current operating system:
path.join(a, b): join with the right separator and normalise..path.resolve(...): an absolute pathpath.basename,path.dirname,path.extname
import { readFile } from 'node:fs/promises';
import path from 'node:path';
const file = path.join(import.meta.dirname, 'data', 'cities.json');
const cities = JSON.parse(await readFile(file, 'utf8'));Use path because separators differ (/ vs \ on Windows) and because it normalises segments. When a path includes user input, resolve it and check it stays inside the allowed folder, to block path traversal (../../etc/passwd).
Original UniCircle question. Last reviewed 22 Oct 2026.
