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 or fs.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 šŸ¤—

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months