Script Valley
Node.js: The Complete Runtime
Node.js Core ModulesLesson 3.1

Node.js fs module: reading, writing, and watching files

fs.readFile, fs.writeFile, fs.appendFile, fs.unlink, fs.mkdir, fs.readdir, fs.stat, fs.watch, fs.promises API, recursive directory creation

The fs Module Covers All File Operations

The built-in fs module handles every file system operation. Always use fs.promises in production โ€” never the sync variants inside request handlers.

const fs = require('fs').promises;

const content = await fs.readFile('./config.json', 'utf8');
await fs.writeFile('./output.txt', 'Hello World', 'utf8');
await fs.appendFile('./log.txt', new Date().toISOString() + ' - event\n');
await fs.unlink('./temp.txt');
await fs.mkdir('./logs/2024', { recursive: true });
const files = await fs.readdir('./src');
const stat = await fs.stat('./data.txt');
console.log(stat.size, stat.mtime);

Watching Files for Changes

const watcher = fs.watch('./config.json', (eventType, filename) => {
  console.log(filename + ' changed: ' + eventType);
});
watcher.close();

fs.watch behavior is not consistent across platforms. For production file watching use the chokidar package, which normalizes behavior across macOS, Linux, and Windows.

Up next

Node.js path module: handling file paths correctly cross-platform

Sign in to track progress

Node.js fs module: reading, writing, and watching files โ€” Node.js Core Modules โ€” Node.js: The Complete Runtime โ€” Script Valley โ€” Script Valley