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.