The fs (file system) module reads, writes and manages files and folders.
Three styles
- Promises (recommended):
import { readFile } from 'node:fs/promises'withawait - Callbacks:
fs.readFile(path, cb) - Sync:
fs.readFileSync(path)— blocks everything; fine for small scripts, avoid in servers
Common functions
readFile(path, 'utf8')— read textwriteFile(path, data)— create or replaceappendFile(path, data)— add to the endmkdir(path, { recursive: true })— create foldersreaddir(path)— list a folderstat(path)— size, dates, isFile()rename(old, new),unlink(path)(delete file),rm(path, { recursive: true })
JSON files
JSON.parse(await readFile('data.json', 'utf8')) and writeFile('data.json', JSON.stringify(obj, null, 2)).
Errors
Wrap in try/catch. A missing file gives error code ENOENT.
Example
Example — A simple JSON notes store
JavaScript
import { readFile, writeFile, mkdir } from 'node:fs/promises';
const FILE = 'data/notes.json';
async function loadNotes() {
try {
return JSON.parse(await readFile(FILE, 'utf8'));
} catch (err) {
if (err.code === 'ENOENT') return []; // file does not exist yet
throw err;
}
}
async function addNote(text) {
const notes = await loadNotes();
notes.push({ id: notes.length + 1, text, createdAt: new Date().toISOString() });
await mkdir('data', { recursive: true });
await writeFile(FILE, JSON.stringify(notes, null, 2));
return notes;
}
const notes = await addNote('Learn the fs module');
console.log(`You have ${notes.length} note(s)`);
The first run creates data/notes.json and prints "You have 1 note(s)". Each run adds another note to the file.