Loading

Quipoin Menu

Learn • Practice • Grow

node-js / Writing Files
interview

Q1. How do you write to a file asynchronously?
Use fs.writeFile() which overwrites the file if it exists. Example:
fs.writeFile('output.txt', 'Hello World', 'utf8', (err) => { if (err) throw err; console.log('File written'); });
For appending, use fs.appendFile(). You can also specify flags like 'a' for append in options.

Q2. How do you write to a file synchronously?
Use fs.writeFileSync(). Example:
try { fs.writeFileSync('output.txt', 'Hello World'); console.log('File written'); } catch (err) { console.error(err); }
. This blocks the event loop until the write completes, so use with caution in production. It's simpler for scripts.

Q3. How do you append to a file?
Use fs.appendFile() (async) or fs.appendFileSync() (sync). Example:
fs.appendFile('log.txt', 'New log entryn', (err) => { if (err) throw err; });
This adds content to the end of the file without overwriting existing content. Alternatively, you can use fs.writeFile with flag: 'a'.

Q4. How do you write using streams?
For writing large amounts of data, use fs.createWriteStream(). Example:
const writeStream = fs.createWriteStream('output.txt'); writeStream.write('Hello '); writeStream.write('World'); writeStream.end(); writeStream.on('finish', () => { console.log('Done'); });
This is memory-efficient and handles backpressure automatically.

Q5. What flags can you use with file writing operations?
Common flags: 'w' - open for writing (default, truncates), 'wx' - like 'w' but fails if file exists, 'a' - open for appending, 'ax' - like 'a' but fails if file exists, 'r+' - open for reading and writing. You can specify these in the options object:
fs.writeFile('file', data, { flag: 'a' }, callback);