Reading & Writing Files (fs)
The `fs` (File System) module lets Node.js interact with files: reading, writing, appending, and deleting them, both synchronously and asynchronously.
Asynchronous methods are preferred in real applications because they don't block the rest of the program while waiting for disk I/O.
Reading files
`fs.readFile()` reads a file asynchronously with a callback; `fs.readFileSync()` blocks until done and returns the data directly.
Writing files
`fs.writeFile()` writes data to a file, creating it if it doesn't exist, or overwriting it if it does.
const fs = require('fs');
fs.readFile('data.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});Hello file contentsreadFile is asynchronous; the callback runs once the file is loaded.
fs.writeFile('out.txt', 'Saved!', (err) => {
if (err) throw err;
console.log('File written');
});File writtenwriteFile creates or overwrites out.txt with the given content.
Key points
- fs module handles file reading and writing.
- Async methods (readFile/writeFile) don't block execution.
- Sync methods (readFileSync/writeFileSync) block until finished.
- Always encode as 'utf8' to get readable text instead of a Buffer.
