← Back to Node.js, page 1

nodejs-0015 · Easy fresher

What are the three styles of the fs API (callback, sync, promises), and which should you use?

fs offers callback functions, synchronous functions ending in Sync, and promise functions in fs/promises. Use the promise API in application code, the Sync versions only at start-up or in scripts, and keep callbacks for old code. File errors carry a code such as ENOENT that you can check.

Full answer

Every common file operation exists in three forms:

  • Callback: fs.readFile(path, cb). The original style. The callback receives (err, data).
  • Synchronous: fs.readFileSync(path). Blocks the event loop until the work is done and throws on error.
  • Promise: require('node:fs/promises').readFile(path). Returns a promise, works with await and try/catch.

Pick the promise API by default. It is clean to write, keeps the event loop free, and fits async functions. Use Sync functions when blocking is harmless: reading a config file at start-up, in a CLI tool, or in a build script. Never use them inside a request handler.

Errors are Error objects with a code property. Common ones: ENOENT (no such file or directory), EACCES (permission denied), EEXIST (already exists), EISDIR (is a directory), ENOTEMPTY (directory not empty), EMFILE (too many open files). Check err.code, not the message text, because messages can change.

Always pass an encoding ('utf8') to get a string. Without it you get a Buffer. Paths are relative to the current working directory of the process, not to the file, so build absolute paths with path.join(__dirname, ...) when it matters.

javascript
const fs = require('node:fs');
const fsp = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');

async function main() {
  const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fs-demo-'));
  const file = path.join(dir, 'attendance.txt');

  // Promise style
  await fsp.writeFile(file, 'present: 28\nabsent: 2\n');
  const text = await fsp.readFile(file, 'utf8');
  console.log('promise read:', JSON.stringify(text));

  // Sync style (blocks, so keep it for start-up code)
  console.log('sync size:', fs.statSync(file).size, 'bytes');

  // Callback style
  await new Promise((resolve) => {
    fs.readFile(file, 'utf8', (err, data) => {
      console.log('callback lines:', data.trim().split('\n').length);
      resolve();
    });
  });

  // Error codes
  try {
    await fsp.readFile(path.join(dir, 'missing.txt'), 'utf8');
  } catch (err) {
    console.log('error code:', err.code);
  }

  await fsp.rm(dir, { recursive: true });
}

main();

The snippet works in a temporary folder and removes it at the end. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): promise read: "present: 28\nabsent: 2\n" sync size: 22 bytes callback lines: 2 error code: ENOENT

Key points

  • Three styles: callback, Sync, and promises (fs/promises).
  • Promise API is the default choice. Sync only when blocking is acceptable.
  • Check error.code values such as ENOENT.
  • Without an encoding you get a Buffer.

Common mistakes

  • Using readFileSync inside an HTTP request handler.
  • Matching error messages instead of err.code.
  • Using a relative path and getting ENOENT because the working directory is different.
  • Forgetting the encoding and being surprised by a Buffer.

Follow-ups

  • How do you read a JSON file safely?
  • What does EMFILE mean and how do you avoid it?
  • Why can fs.promises.readFile still block the thread pool?

Tips

  • State a clear rule for when Sync is fine.
  • Mention ENOENT by name.
  • Show the same operation in two styles to prove you know both.