Writing To Files In Node.js

Write or append files in Node.js using fs.writeFile(), fs.appendFile(), Promises or Streams. Choose the method based on file size, frequency and use case.

Summarize with AI

Not enough time? get the key points instantly.

Writing to files is a common task in Nodejs development, whether for logging, saving uploads or creating reports. Node.js has various methods through the built-in fs (File System) module to write or append data both synchronously and asynchronously.

Method 1: Using fs.writeFile()

This creates or overwrites a file asynchronously:

js

const fs = require(‘fs’);fs.writeFile(‘output.txt’, ‘Hello eSparkBiz!’, (err) => {if (err) throw err;

console.log(‘File written successfully’);

});

Method 2: Using fs.appendFile()

Use this to add content to an existing file:

js

fs.appendFile(‘output.txt’, ‘\nMore content here…’, (err) => {if (err) throw err;

console.log(‘Content appended!’);

});

Method 3: Using Promises with fs.promises

Modern alternative for cleaner async code:

js

const fs = require(‘fs’).promises;async function writeFile() {

await fs.writeFile(‘output.txt’, ‘Written with promises!’);

}

writeFile();

Method 4: Using Writable Streams

Recommended for large data writes or continuous output:

js

const stream = fs.createWriteStream(‘bigfile.txt’);stream.write(‘Chunk 1\n’);

stream.end(‘Final chunk’);

Also Read: How to Remove a File in Node.js

Conclusion

Use fs.writeFile() or Promises for simple tasks. Use streams for writing large files in Node.js apps.


Resources

Insights from our engineering leaders.

Our team shares practical insights on the technologies and engineering decisions shaping enterprise software today, grounded in real client work.

NodeJS

Which Company Is Best for Hiring Node.js Developers in the UK?

Node.js helps businesses build backend systems, REST APIs, real-time applications, and SaaS platforms using JavaScript. Developing these solutions requires professionals who understand application architecture, technical…

NodeJS

How to tell if Node.js is installed or not?

To verify Node.js installation, run node -v or node --version. This checks if Node.js is installed and working correctly. Problem Before you run any Node.js…