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.
Need expert help handling file operations in Node.js?
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.
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’);
});
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!’);
});
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
Recommended for large data writes or continuous output:
js
const stream = fs.createWriteStream(‘bigfile.txt’);stream.write(‘Chunk 1\n’);
stream.end(‘Final chunk’);
Use fs.writeFile() or Promises for simple tasks. Use streams for writing large files in Node.js apps.
eSparkBiz is rated 4.9 Stars
Real People, Real Stories
See why 300+ startups & enterprises trust eSparkBiz with their software outsourcingHiring 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…
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…
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…
Let’s discuss how our dedicated experts can help.