Skip to the page

Events, buffers, streams and files · core

Files and paths, safely

Use the promise-based fs API or streams in servers, build paths with path.join or path.resolve, and never put user input into a file path without checking the final path, because '../' can escape your folder.

The notes

What you must know

  • Three styles: node:fs/promises (await fs.readFile), callbacks (fs.readFile(path, cb)), sync (fs.readFileSync). Servers use promises or streams; sync is for startup and CLI scripts.
  • path.join joins and normalises segments; path.resolve returns an absolute path (using the current working directory if needed).
  • process.cwd() is where node was started; __dirname (CommonJS) or import.meta.dirname (ESM) is the folder of the current file.
  • Path traversal: path.join(uploadsDir, req.params.name) with name '../../etc/passwd' escapes the folder. Resolve the path, then check it is still inside the base folder (or only accept generated ids).
  • Write to a temp file and rename it for an atomic replace; fs.mkdir(dir, { recursive: true }); fs.rm(dir, { recursive: true, force: true }).
  • Open file handles are limited (EMFILE: too many open files). Streams and readFile close them; close any FileHandle you open yourself.

The red pen

Common traps: mistake → fix

  • Mistake: process.cwd() is the folder of the current file

    Fix: it is where the process started; use __dirname or import.meta.dirname.

  • Mistake: path.join protects against ../

    Fix: it normalises '../' happily; check the final resolved path.

  • Mistake: readFileSync is faster, so use it everywhere

    Fix: it blocks every other request while the disk works.

Easy to hard

Questions interviewers ask, easy to hard

  1. readFile vs readFileSync vs createReadStream: when do you use each?
  2. path.join vs path.resolve?
  3. How do you stop path traversal in a file download endpoint?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview