Writing files with Node

By

Learn how to write files in Node.js with the fs module, using writeFile() and writeFileSync(), the promises API, file flags, appendFile(), and streams.

~~~

The easiest way to write to files in Node.js is to use the fs.writeFile() API.

Example:

const fs = require('fs')

const content = 'Some content!'

fs.writeFile('/Users/flavio/test.txt', content, (err) => {
  if (err) {
    console.error(err)
    return
  }
  //file written successfully
})

Alternatively, you can use the synchronous version fs.writeFileSync():

const fs = require('fs')

const content = 'Some content!'

try {
  const data = fs.writeFileSync('/Users/flavio/test.txt', content)
  //file written successfully
} catch (err) {
  console.error(err)
}

By default, this API will replace the contents of the file if it does already exist.

You can modify the default by specifying a flag:

fs.writeFile('/Users/flavio/test.txt', content, { flag: 'a+' }, (err) => {})

The flags you’ll likely use are

(you can find more flags at https://nodejs.org/api/fs.html#fs_file_system_flags)

The promises version

The node:fs/promises module gives you the same functions as promises, so you can await them instead of passing a callback:

import fs from 'node:fs/promises'

const content = 'Some content!'

try {
  await fs.writeFile('/Users/flavio/test.txt', content)
} catch (err) {
  console.error(err)
}

Top-level await works in ES modules. In CommonJS you can still use require('node:fs/promises') and wrap the call in an async function.

It takes the same options, so { flag: 'a+' } works here too.

Append to a file

A handy method to append content to the end of a file is fs.appendFile() (and its fs.appendFileSync() counterpart):

const content = 'Some content!'

fs.appendFile('file.log', content, (err) => {
  if (err) {
    console.error(err)
    return
  }
  //done!
})

Same idea with promises:

import fs from 'node:fs/promises'

await fs.appendFile('file.log', 'Some content!\n')

Using streams

All those methods write the full content to the file before returning the control back to your program (in the async version, this means executing the callback)

In this case, a better option is to write the file content using streams.

Tagged: Node.js · All topics

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about node: