This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Node.js fs Module Cheatsheet

A quick reference guide for Node.js fs: asynchronous and synchronous file reading, writing, watching, stats, file descriptors, and directory operations.

· Published

The Node.js fs (File System) module provides APIs for interacting with the local file system using Promises, callbacks, or synchronous execution.

Promise-Based API (Modern ESM / CJS)

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

// Read file as UTF-8 string
const content = await fs.readFile('data.txt', 'utf8');

// Write or replace file contents
await fs.writeFile('output.txt', 'Hello World', 'utf8');

// Append to file
await fs.appendFile('log.txt', 'New entry\n', 'utf8');

// Check existence & access permissions
try {
  await fs.access('config.json');
} catch {
  console.log('File does not exist or cannot be accessed');
}

Synchronous API

const fs = require('fs');

const data = fs.readFileSync('input.txt', 'utf8');
fs.writeFileSync('output.txt', data);
fs.appendFileSync('output.txt', '\nappended');

const exists = fs.existsSync('file.txt');

File Metadata & Stats

const stats = await fs.stat('file.txt');

stats.isFile();            // -> true / false
stats.isDirectory();       // -> true / false
stats.isSymbolicLink();    // -> true / false
stats.size;                // File size in bytes
stats.mtime;               // Last modified timestamp

Directory Operations

// List directory entries
const files = await fs.readdir('src/');

// Recursive directory creation
await fs.mkdir('build/assets/css', { recursive: true });

// Recursive directory removal
await fs.rm('dist/', { recursive: true, force: true });

File System Watching

const fs = require('fs');

const watcher = fs.watch('src/', { recursive: true }, (eventType, filename) => {
  console.log(`Event: ${eventType} on ${filename}`);
});

// Stop watching
watcher.close();

References

Related topics