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.

Writing to files is a common task in Node.js, 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();
Also Read: How To Update Node JS To Latest Version

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');

Conclusion

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

If you’re trying to run nodemon from the terminal and see the error: nodemon: command not found, it usually means the nodemon package is not…

10 Oct, 2025

Startups succeed when they move fast and that requires the right technology. Node.js Developers have become the backbone for agile teams, powering scalable, high-performance apps…

24 Sep, 2025

Node.js has become the backbone of modern web applications, powering scalable platforms across Europe. Its efficiency and speed make it ideal for fintech, SaaS, e-commerce…

24 Sep, 2025
Request a Quote Schedule a Meeting