De Node.js fs-module (File System) biedt API's voor interactie met het lokale bestandssysteem via Promises, callbacks of synchrone uitvoering.
Promise-gebaseerde API (fs/promises)
const fs = require('fs/promises');
// import fs from 'node:fs/promises';
// Bestand lezen als UTF-8 string
const content = await fs.readFile('data.txt', 'utf8');
// Bestand schrijven of vervangen
await fs.writeFile('output.txt', 'Hello World', 'utf8');
// Tekst toevoegen aan bestand
await fs.appendFile('log.txt', 'New entry\n', 'utf8');
// Bestaan en toegangsrechten controleren
try {
await fs.access('config.json');
} catch {
console.log('Bestand bestaat niet of is niet toegankelijk');
}
Synchrone 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');
Bestandsmetadata en Statistieken (fs.stat)
const stats = await fs.stat('file.txt');
stats.isFile(); // -> regulier bestand (true / false)
stats.isDirectory(); // -> map (true / false)
stats.isSymbolicLink(); // -> symbolische link (true / false)
stats.size; // Bestandsgrootte in bytes
stats.mtime; // Tijdstempel van laatste wijziging
Mapbewerkingen
// Inhoud van map opvragen
const files = await fs.readdir('src/');
// Recursief mappen aanmaken
await fs.mkdir('build/assets/css', { recursive: true });
// Recursief mappen verwijderen
await fs.rm('dist/', { recursive: true, force: true });
Bestandssysteem Monitoren (fs.watch)
const fs = require('fs');
const watcher = fs.watch('src/', { recursive: true }, (eventType, filename) => {
console.log(`Event: ${eventType} on ${filename}`);
});
// Monitoren stoppen
watcher.close();
Bestandsdescriptors (File Descriptors)
const fs = require('fs/promises');
// Alleen-lezen openen
const filehandle = await fs.open('archive.bin', 'r');
// 1024-byte buffer toewijzen
const buffer = Buffer.alloc(1024);
// Bytes in buffer inlezen
const { bytesRead } = await filehandle.read(buffer, 0, 1024, 0);
await filehandle.close();