How to append data to a file in Node.js

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) {

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) => {

// end stream

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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.