Skip to content
UniCircle
EasyConceptualBuilt-in modules

The fs and path modules

Question NODE-FS-001

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, appendFile
  • mkdir (with { recursive: true }), readdir, stat, rm
  • createReadStream, createWriteStream for 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 path
  • path.basename, path.dirname, path.extname
JavaScript
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.