Writing file in Node Js using createWriteStream and writeFile API
You might have already come across fs.writeFile
or fs.writeFileSync
API to write files in Node Js.
const fs = require('fs')
fs.writeFile('message.txt', 'Hello Next Js, sorry Node Js', (err) => {
if (err) throw err
console.log('The file has been saved!')
})
const fs = require('fs')
fs.writeFileSync('message.txt', 'Hi Afrin!')
When to use fs.writeFile
or fs.writeFileSync
API?
fs.writeFile
orfs.writeFileSync
API is useful when you want to write small files.- for writing large files, it will block the event loop and consume more memory.
But there is another API fs.createWriteStream
which is more efficient and faster because it writes data in chunks not all at once like fs.writeFile
or fs.writeFileSync
API.
Let's see how we can use fs.createWriteStream
API to write files.
const fs = require('fs')
const writeStream = fs.createWriteStream('message.txt')
writeStream.write('Hi Prajan!', (err) => {
if (err) throw err
console.log('The file has been saved!')
})
writeStream.end()
fs.createWriteStream
API returns a write stream object which is an event emitter. It emits finish
event when all data has been flushed to the underlying system.
const fs = require('fs')
const writeStream = fs.createWriteStream('message.txt')
writeStream.on('finish', () => {
console.log('The file has been saved!')
})
writeStream.write('Hi Prajan!')
writeStream.end()
Hope you find this article useful and learnt a trick around writing files in node Js š¤