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

Hiring skilled Node.js developers is essential for building modern, high performing web and backend systems. Their expertise ensures faster development, scalability and stability, which are…

06 Feb 2026

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…

22 Jan 2026

Problem Node.js is single-threaded, so it can’t use multiple cores. In clustered apps, microservices or when spawning repeatable child processes, you need a way for…

16 Jan 2026