Q1. What is the fs module in Node.js?
The fs (file system) module provides an API for interacting with the file system. It's a core module that allows reading, writing, deleting, and manipulating files and directories. You include it with:
const fs = require('fs'). It offers both synchronous and asynchronous methods, with the asynchronous versions being preferred for performance.Q2. What's the difference between synchronous and asynchronous fs methods?
Synchronous methods (like fs.readFileSync) block the event loop until the operation completes. Asynchronous methods (like fs.readFile) don't block; they take a callback that executes when the operation finishes. Asynchronous methods are preferred in production because they allow Node.js to handle other requests during I/O operations.
Q3. How do you read a file asynchronously?
Use fs.readFile(path, encoding, callback). Example:
fs.readFile('file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); }); The callback receives error (if any) and the file data. If encoding is not specified, a buffer is returned. Always handle errors properly.Q4. How do you write to a file?
Use fs.writeFile(file, data, options, callback). It overwrites the file if it exists. Example:
fs.writeFile('output.txt', 'Hello World', 'utf8', (err) => { if (err) throw err; console.log('File saved'); }); For appending, use fs.appendFile. Options can include encoding, mode, and flag.Q5. What is the fs.promises API?
fs.promises provides promise-based versions of fs methods, allowing you to use async/await. Example:
const fs = require('fs').promises; async function read() { const data = await fs.readFile('file.txt', 'utf8'); console.log(data); }. This makes asynchronous code more readable and easier to handle with try/catch.