Rez Moss

Rez Moss

Digital Reflections: Exploring Tech, Innovation & Ideas

Node.js fs Module: Read, Write, Append and Delete Files (Examples)

Aug 2017

Node.js works with files through the built-in fs module. The modern way is the promise API from node:fs/promises: readFile to read, writeFile to create or replace, appendFile to add to the end, unlink to delete, all used with await. The older callback versions (fs.readFile(path, cb)) and sync versions (fs.readFileSync) do the same things in different styles.

Below are the operations you’ll use most, in one script I ran on Node 22. The output comes from that run.

Reading, writing and appending

const fs = require('node:fs/promises');

async function main() {
  await fs.writeFile('output.txt', 'Hello, Node.js!\n');
  await fs.appendFile('output.txt', 'Second line\n');

  const text = await fs.readFile('output.txt', 'utf8');
  console.log(JSON.stringify(text)); // "Hello, Node.js!\nSecond line\n"

  const lines = text.split('\n').filter(Boolean);
  console.log(lines.length, 'lines'); // 2 lines
}

main();

writeFile creates the file if it’s missing and replaces it if it exists, so be sure that’s what you want. appendFile also creates the file if needed, which makes it handy for simple logs. Pass 'utf8' to readFile to get a string. Leave it out and you get a Buffer of raw bytes, which is what you want for images and other binary files.

readFile loads the whole file into memory. That’s fine for config files and normal documents. For a multi-gigabyte log, use fs.createReadStream from node:fs and process it in chunks instead.

Handling errors and checking if a file exists

Every fs call can fail, and the error has a code that tells you why. A missing file gives ENOENT:

try {
  await fs.readFile('missing.txt', 'utf8');
} catch (err) {
  console.log(err.code); // ENOENT
}

Other codes you’ll meet are EACCES (no permission), EISDIR (it’s a folder) and EEXIST (already exists). Check err.code and handle the ones you expect, and rethrow the rest.

To check whether a file exists without reading it, fs.access throws if it doesn’t. Wrapped in a small helper:

async function exists(p) {
  try {
    await fs.access(p);
    return true;
  } catch {
    return false;
  }
}

console.log(await exists('output.txt'), await exists('missing.txt')); // true false

The sync existsSync from node:fs is still fine for startup checks. But if you’re about to open the file anyway, skip the check and just open it inside try/catch. Checking first leaves a gap where another process can delete or create the file between the check and the open.

Folders, listing and file info

mkdir with recursive: true creates every missing parent folder and doesn’t complain if the folder already exists. readdir lists a folder, and with recursive: true it walks the subfolders too:

const path = require('node:path');

await fs.mkdir(path.join('logs', '2026'), { recursive: true });
await fs.writeFile(path.join('logs', '2026', 'app.log'), 'ok\n');
console.log(await fs.readdir('logs', { recursive: true }));
// [ '2026', '2026/app.log' ]

Use path.join instead of gluing strings with /, so the same code works on Windows.

stat gives size, timestamps and type:

const st = await fs.stat('output.txt');
console.log(st.size, st.isFile(), st.isDirectory()); // 28 true false

Renaming and deleting

await fs.rename('output.txt', 'renamed.txt');
await fs.unlink('renamed.txt');
await fs.rm('logs', { recursive: true, force: true });

rename also moves a file to another folder on the same disk. unlink deletes one file. rm with recursive: true deletes a folder and everything in it, and force: true stops it from throwing if the folder isn’t there. That last one is the rm -rf of Node, so double-check the path you pass it.

Callbacks, promises or sync?

All three APIs call the same code underneath. I use fs/promises with await for anything that runs while a server is handling requests, because a sync call blocks the event loop and every other request waits. Sync calls like readFileSync are fine in CLI scripts and at startup, before the server is listening. The callback style is what you’ll see in older code and tutorials. Node.js callbacks explained shows how it maps to promises.

For JSON files specifically, with pretty printing and safe parsing, see Node.js JSON: parse, stringify, read and write. And to serve files over HTTP, a Node.js web server without Express reads an HTML file with the same readFile call.

comments powered by Disqus