Skip to main content

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.

javascript
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.

javascript
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:

javascript
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:

javascript
import fs from 'fs'; fs.appendFile('./log.txt', 'A new entry\n', (err) => { if (err) throw err; console.log('Entry appended!'); });

or with await:

javascript
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.

javascript
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.

javascript
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:

javascript
{ encoding: 'utf8', // encoding mode: 0o666, // file permissions flag: 'w' // mode: 'w' = write, 'a' = append, 'wx' = write only if the file doesn't exist }

Example:

javascript
await writeFile('./data.txt', 'Test', { flag: 'a', encoding: 'utf8' });

7. Example: writing an object to a JSON file

javascript
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 → writeFile again.

8. Checking existence before writing

javascript
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:

javascript
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)

javascript
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

MethodAsynchronousOverwritesAppendsStreamingRecommended
fs.writeFileYesYesNoNoYes
fs/promises.writeFileYes (await)YesNoNoYes, the best option
fs.appendFileYesNoYesNoYes
fs.createWriteStreamYesConfigurableYesYesYes (large data)
fs.writeFileSyncNoYesNoNoCLI only

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.