Server JavaScript reads configs, logs, and uploads from disk. node:path builds cross-platform paths; node:fs reads and writes files—prefer promise APIs with async/await.
path essentials
import path from 'node:path';
path.join('data', 'users', 'ada.json');
path.basename('/tmp/report.txt'); // report.txt
path.extname('photo.png'); // .png
Always join segments with path.join—never hard-code \ or / for portability.
fs promises
import { writeFile, readFile } from 'node:fs/promises';
await writeFile('note.txt', 'Hello', 'utf8');
const text = await readFile('note.txt', 'utf8');
Safety
Never pass raw user input into file paths without validation—path traversal attacks use ../ to escape intended directories.
Important interview questions and answers
- Q: readFileSync vs readFile?
A: Sync blocks the event loop; asyncfs.promisesyields during I/O—prefer async in servers. - Q: path.join vs string concat?
A:joinnormalizes separators and..safely for the OS.
Self-check
- Why avoid sync fs in request handlers?
- What does path.basename return?