The fs module also handles directories: creating, reading their contents, and removing them. fs.watch() lets you monitor files or directories for changes in real time.
Use fs.readdir() with the withFileTypes option to distinguish files from subdirectories.
Example
const fs = require('fs/promises');
const fsSync = require('fs');
const path = require('path');
async function dirDemo() {
const dir = path.join(__dirname, 'temp-dir');
// Create a directory (recursive: true won't throw if it exists):
await fs.mkdir(dir, { recursive: true });
// Write a couple of files inside it:
await fs.writeFile(path.join(dir, 'a.txt'), 'File A');
await fs.writeFile(path.join(dir, 'b.txt'), 'File B');
// Read directory entries:
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const type = entry.isDirectory() ? 'DIR ' : 'FILE';
console.log(`${type} ${entry.name}`);
}
// Remove a directory and all contents (Node 14.14+):
await fs.rm(dir, { recursive: true, force: true });
console.log('Directory removed.');
}
dirDemo().catch(console.error);
// Watch a file for changes:
const watcher = fsSync.watch('data.txt', (eventType, filename) => {
console.log(`Event: ${eventType} on ${filename}`);
});
// Stop watching after 10 seconds:
setTimeout(() => watcher.close(), 10_000);