The fs module allows interacting with the file system in Node.js.
fs
1. Importing fs Module
const fs = require('fs');
Read File:
fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });
Sync:
const data = fs.readFileSync('file.txt', 'utf8'); console.log(data);
Write to File:
fs.writeFile('file.txt', 'Hello!', (err) => { if (err) throw err; });
fs.writeFileSync('file.txt', 'Hello!');
Delete File:
fs.unlink('file.txt', (err) => { if (err) throw err; });
fs.unlinkSync('file.txt');
Create Directory:
fs.mkdir('newDir', (err) => { if (err) throw err; });
Remove Directory:
fs.rmdir('newDir', (err) => { if (err) throw err; });
Conclusion
The fs module lets you perform file operations like reading, writing, deleting, and more, both asynchronously and synchronously.