Node.js Append to a File

To append data to a file in Node.js, use the fs.appendFile() function for asynchronous file operations or fs.appendFileSync() for synchronous file operations. Both functions add new data at the end of the file and create the file if it does not already exist.

Appending is useful when you want to add log entries, save records line by line, write audit messages, or keep adding text without replacing the existing file content. This tutorial explains the syntax, options, examples, newline handling, and common mistakes when appending data using the Node.js File System module.

In this tutorial, we shall learn

Node.js Append File

How Node.js appends data using the fs module

The Node.js fs module provides file system functions. When you call appendFile() or appendFileSync(), Node opens the file in append mode, writes the supplied data after the existing content, and then completes the operation. The existing content is not overwritten.

For most application code, prefer the asynchronous version because it does not block the event loop while the file operation is in progress. Use the synchronous version only in scripts, startup tasks, small utilities, or places where blocking execution is acceptable.

Syntax of fs.appendFile() in Node.js

The syntax of appendFile() function is

</>
Copy
fs.appendFile(filepath, data, options, callback_function);

Callback function is mandatory and is called when appending data to file is completed.

The callback receives an error object as its first argument. If the append operation succeeds, the error value is null or undefined. If the operation fails, handle the error instead of assuming that the file was updated.

Syntax of fs.appendFileSync() in Node.js

The syntax of appendFileSync() function is

</>
Copy
fs.appendFileSync(filepath, data, options);

where :

  • filepath [mandatory] is a String that specifies file path
  • data [mandatory] is what you append to the file
  • options [optional] to specify encoding/mode/flag

Note : If file specified does not exist, a new file is created with the name provided, and data is appended to the file.

Node.js appendFile() parameters and options

The options argument can be a string encoding such as 'utf8', or an object that describes how the file should be opened and written.

ParameterMeaning in Node.js file append operation
filepathPath of the file where data has to be appended. It may be a relative path such as 'sample.txt' or an absolute path.
dataText, Buffer, or supported data value that has to be written at the end of the file.
options.encodingCharacter encoding used when data is a string. 'utf8' is commonly used for text files.
options.modeFile permission mode used when Node has to create a new file.
options.flagFile system flag. The append functions use append behavior, commonly represented by the 'a' flag.
callback_functionFunction called after fs.appendFile() finishes. It should check the error argument.

Example 1 – Node.js Append data to file asynchronously using appendFile()

To append data to a file asynchronously in Node.js, use appendFile() function of Node FS as shown below.

nodejs-append-to-file-example.js

</>
Copy
// Example Node.js program to append data to file
var fs = require('fs');

var data = "\nLearn Node.js with the help of well built Node.js Tutorial.";

// append data to file
fs.appendFile('sample.txt',data, 'utf8',
	// callback function
	function(err) {		
		if (err) throw err;
		// if no error
		console.log("Data is appended to file successfully.")
});

Output

arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-append-to-file-example.js
Data is appended to file successfully.

File before appending

Welcome to www.tutorialkart.com.

File after appending

Welcome to www.tutorialkart.com.
Learn Node.js with the help of well built Node.js Tutorial.

In this example, the data string begins with \n. This moves the appended text to a new line. Node.js does not automatically add a line break when appending data.

Example 2 – Node.js Append data to file synchronously using appendFileSync()

To append data to a file synchronously in Node.js, use appendFileSync() function of Node FS as shown below.

nodejs-append-to-file-example-2.js

</>
Copy
// Example Node.js program to append data to file
var fs = require('fs');

var data = "\nLearn Node.js with the help of well built Node.js Tutorial.";

// append data to file
fs.appendFileSync('sample.txt',data, 'utf8');
console.log("Data is appended to file successfully.")

Output

arjun@arjun-VPCEH26EN:~/nodejs$ node nodejs-append-to-file-example-2.js
Data is appended to file successfully.

File before appending

Welcome to www.tutorialkart.com.

File after appending

Welcome to www.tutorialkart.com.
Learn Node.js with the help of well built Node.js Tutorial.

The synchronous method is shorter, but it blocks the running JavaScript thread until the file write finishes. Avoid it inside a web request handler when many users may access the application at the same time.

Append data with fs.promises.appendFile() and async/await

Modern Node.js code often uses promises with async and await. The promise-based API keeps the file operation asynchronous while making the control flow easier to read.

nodejs-append-promises-example.js

</>
Copy
const fs = require('fs/promises');

async function addLogEntry(message) {
  const line = `${new Date().toISOString()} - ${message}\n`;

  try {
    await fs.appendFile('app.log', line, { encoding: 'utf8' });
    console.log('Log entry appended.');
  } catch (error) {
    console.error('Could not append log entry:', error.message);
  }
}

addLogEntry('User signed in');

Output

Log entry appended.

After running the program more than once, app.log will contain multiple lines because every call writes at the end of the same file.

Adding each appended value on a new line in Node.js

appendFile() writes exactly the data you pass to it. If you want each record on a separate line, add a newline character yourself. On most systems, \n is enough for text files.

</>
Copy
const fs = require('fs');

const name = 'Ravi';
const score = 82;

fs.appendFile('scores.txt', `${name},${score}\n`, 'utf8', (err) => {
  if (err) {
    console.error('Append failed:', err.message);
    return;
  }

  console.log('Score saved.');
});

scores.txt after three successful appends

Ravi,82
Meena,91
Arun,76

Append JSON data to a file in Node.js

When appending JSON records, avoid appending several full JSON objects directly into one file unless you are intentionally creating a newline-delimited JSON file. A common pattern is to write one JSON object per line.

</>
Copy
const fs = require('fs');

const event = {
  type: 'payment',
  status: 'success',
  amount: 1200
};

const line = JSON.stringify(event) + '\n';

fs.appendFile('events.ndjson', line, 'utf8', (err) => {
  if (err) {
    console.error('Unable to append event:', err.message);
    return;
  }

  console.log('Event appended.');
});

events.ndjson

{"type":"payment","status":"success","amount":1200}

This format is easier to append safely because each line is a separate JSON value. A normal JSON array, on the other hand, usually has to be read, parsed, modified, and written back as a complete file.

appendFile() vs writeFile() in Node.js

Use appendFile() when the existing file content must remain and the new data should be added at the end. Use writeFile() when you want to replace the file content or create a fresh file with new content.

Node.js functionWhat happens to existing content?Typical use
fs.appendFile()Existing content is kept. New data is added at the end.Logs, history files, CSV rows, audit trails, line-by-line records.
fs.writeFile()Existing content is replaced unless you use a custom append flag.Saving a complete file, overwriting generated output, writing configuration snapshots.

Common Node.js appendFile() errors and practical fixes

If appending to a file fails, the callback or promise rejection usually tells you why. The table below lists common causes.

Problem while appending a fileLikely reasonFix
ENOENT errorThe directory path does not exist. appendFile() can create the file, but it cannot create all missing parent directories by itself.Create the directory first, or check the path before appending.
EACCES or permission errorThe Node.js process does not have permission to write to the target location.Use a writable directory, change permissions carefully, or run the process with the correct user.
Text appears on the same lineThe appended string does not include a newline character.Add \n before or after the appended text, depending on the file format.
Unexpected overwritewriteFile() was used instead of appendFile(), or a wrong file flag was supplied.Use appendFile() for append-only behavior.

Checklist for reviewing Node.js file append code

  • Use fs.appendFile() or fs.promises.appendFile() for non-blocking application code.
  • Use fs.appendFileSync() only when blocking the current process is acceptable.
  • Add \n explicitly when every appended item should start or end on a new line.
  • Handle callback errors or promise rejections before reporting that the file was updated.
  • Check that the parent directory exists before appending to a nested file path.
  • Do not use writeFile() when the goal is to preserve existing content.

FAQs on appending data to a file in Node.js

How do I append data to an existing file in Node.js?

Use fs.appendFile('file.txt', data, 'utf8', callback) for asynchronous appending. If you prefer promise-based code, use fs.promises.appendFile() with await.

Does Node.js appendFile() create the file if it does not exist?

Yes. If the file path points to a file that does not exist, Node.js creates the file and writes the data. However, the parent directory must already exist.

Does fs.appendFile() automatically add a new line?

No. Node.js appends exactly the data you provide. Add \n to the string when you want the appended data to appear on a separate line.

What is the difference between appendFile() and the Linux >> operator?

The >> operator is used in a shell command to redirect command output to the end of a file. fs.appendFile() is used inside a Node.js program to append data from JavaScript code.

Is fs.appendFile() the same as FormData.append() in JavaScript?

No. fs.appendFile() writes data to a file on the server or local file system in Node.js. FormData.append() adds a field or file to a form payload, usually before sending an HTTP request.

Node.js appendFile and appendFileSync summary

In this Node.js TutorialNode.js Append to a File, we have learnt to append data to a file in Node.js, synchronously and asynchronously using appendFileSync() and appendFile() functions of Node FS respectively with Example Node.js programs.

Use appendFile() or fs.promises.appendFile() for most real application code, because these APIs keep the operation asynchronous. Use appendFileSync() for simple scripts where blocking execution is acceptable. Always include newline characters yourself when the file format requires separate lines.