How do you write data to a file?
1. Asynchronous writing (via a callback)
The classic way, doesn't block the thread, good for servers.
import fs from 'fs';
fs.writeFile('./output.txt', 'Hello, Node.js!', (err) => {
if (err) {
console.error('Write error:', err);
return;
}
console.log('File written successfully!');
});- If the file doesn't exist, Node creates it.
- If it already exists, its content gets overwritten.
- A third argument (
options) can be passed, for example{ flag: 'a' }to append (see below).
2. Asynchronous writing with promises (fs/promises)
The modern, readable, and recommended option.
Works with async/await, no callbacks.
import { writeFile } from 'fs/promises';
try {
await writeFile('./output.txt', 'Hello from fs/promises!');
console.log('File created!');
} catch (err) {
console.error('Error:', err);
}Options can be added:
await writeFile('./log.txt', 'First line\n', { flag: 'a' }); // "append"3. Appending data to the end of a file
To add data rather than overwrite it:
import fs from 'fs';
fs.appendFile('./log.txt', 'A new entry\n', (err) => {
if (err) throw err;
console.log('Entry appended!');
});or with await:
import { appendFile } from 'fs/promises';
await appendFile('./log.txt', 'Added another line\n');4. Synchronous writing (blocking)
Rarely used (for example, when loading configuration). Blocks the event loop, not recommended for server applications.
import fs from 'fs';
try {
fs.writeFileSync('./output.txt', 'Synchronous write');
console.log('File written!');
} catch (err) {
console.error(err);
}Program execution is halted until the file is written.
5. Streaming writes (for large files)
If a large amount of data needs writing (for example, a log or a big JSON file), streams are the better choice.
import fs from 'fs';
const stream = fs.createWriteStream('./bigdata.txt');
stream.write('First line\n');
stream.write('Second line\n');
stream.end('File complete!\n');
stream.on('finish', () => console.log('Write finished!'));
stream.on('error', (err) => console.error('Error:', err));Advantages of streams:
- Writing happens in chunks, no need to hold everything in memory;
- Useful for streaming HTTP responses or logging.
6. Write options (options)
writeFile, appendFile, and createWriteStream accept a settings object:
{
encoding: 'utf8', // encoding
mode: 0o666, // file permissions
flag: 'w' // mode: 'w' = write, 'a' = append, 'wx' = write only if the file doesn't exist
}Example:
await writeFile('./data.txt', 'Test', { flag: 'a', encoding: 'utf8' });7. Example: writing an object to a JSON file
import { writeFile } from 'fs/promises';
const user = { name: 'Tim', age: 28 };
await writeFile('./user.json', JSON.stringify(user, null, 2));
console.log('JSON saved!');JSON.stringify(..., null, 2)produces a nicely indented format.- To update it, read the file → parse → update →
writeFileagain.
8. Checking existence before writing
import fs from 'fs';
if (fs.existsSync('./data.txt')) {
console.log('The file already exists!');
} else {
fs.writeFileSync('./data.txt', 'A new file was created');
}Or asynchronously:
import { access, writeFile } from 'fs/promises';
import { constants } from 'fs';
try {
await access('./data.txt', constants.F_OK);
console.log('The file already exists');
} catch {
await writeFile('./data.txt', 'Created automatically');
}9. A "logger" example (a real use case)
import { appendFile } from 'fs/promises';
async function log(message) {
const timestamp = new Date().toISOString();
await appendFile('./server.log', `[${timestamp}] ${message}\n`);
}
await log('Server started');
await log('A user logged in');A great fit for keeping logs without any libraries.
10. A summary table
| Method | Asynchronous | Overwrites | Appends | Streaming | Recommended |
|---|---|---|---|---|---|
fs.writeFile | Yes | Yes | No | No | Yes |
fs/promises.writeFile | Yes (await) | Yes | No | No | Yes, the best option |
fs.appendFile | Yes | No | Yes | No | Yes |
fs.createWriteStream | Yes | Configurable | Yes | Yes | Yes (large data) |
fs.writeFileSync | No | Yes | No | No | CLI only |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.