To append data to a file in Node.js:

  1. Use the fs.appendFile() method to asynchronously append data to a file.
  2. Pass the file name, the contents to append, and a callback function as first, second, and third parameters.
  3. The fs.appendFile() automatically creates a new file if it doesn't exist.
  4. The callback method gets called with either an error object or null.

Here is an example:

const fs = require('fs')

// append data to a file
fs.appendFile('file.txt', 'Hey there!', err => {
  if (err) {
    throw err
  }
  console.log('File is updated.')
})

If you are appending text to a file that has a different encoding scheme than the default operating system encoding, you should pass the encoding scheme as the 3rd argument:

fs.appendFile('file.txt', 'Hey there!', 'utf8', (err) => { })

The fs module provides another method called fs.appendFileSync() to synchronously append text to a file. It blocks the Node.js event loop until the file append operation is finished.

Here is an example:

const fs = require('fs')

// append data to a file
try {
  fs.appendFileSync('file.txt', 'Hey there!')

  console.log('File is updated.')
} catch (error) {
  console.log(error)
}

Both fs.appendFile() and fs.appendFileSync() methods create a new file handle each time they are called. They are only good for a one-off append operation.

If you want to append repeatedly to the same file, for example, writing in a log file, do not use these methods. Instead, you should use the fs.createWriteStream() method that creates a writable stream and reuses the file handle to append new data.

Here is an example:

const fs = require('fs')

// create a stream
const stream = fs.createWriteStream('file.txt', { flags: 'a' })

// append data to the file
;[...Array(100)].forEach((num, index) => {
  stream.write(`${index}\n`)
})

// end stream
stream.end()

Read this article to learn more about reading and writing files in a Node.js application.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.