
File System in NodeJs
The File System (fs) module in Node.js lets you interact with the file system — reading, writing, updating, deleting files and directories — all using JavaScript.
It comes built-in, so no need to install anything.
✅ Importing the fs
Module
const fs = require('fs/promises');
📖 Common File Operations
📄 1. Read a File (Async)
fs.readFile('example.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data);});
✍️ 2. Write to a File (Async - Overwrites)
fs.writeFile('example.txt', 'Hello, World!', (err) => { if (err) throw err; console.log('File written!');});
➕ 3. Append to a File
fs.appendFile('example.txt', '\nThis is appended text.', (err) => { if (err) throw err; console.log('Content appended!');});
❌ 4. Delete a File
fs.unlink('example.txt', (err) => { if (err) throw err; console.log('File deleted!');});
📁 5. Create a Directory
fs.mkdir('myFolder', (err) => { if (err) throw err; console.log('Directory created!');});
📂 6. Read a Directory
fs.readdir('.', (err, files) => { if (err) throw err; console.log(files);});
🔄 Synchronous Versions
Every function also has a synchronous version with a Sync
suffix:
const data = fs.readFileSync('example.txt', 'utf8');console.log(data);
🚀 Promise-based Usage (fs/promises
)
const fs = require('fs/promises');async function run() { try { const data = await fs.readFile('example.txt', 'utf8'); console.log(data); } catch (err) { console.error(err); }}run();