English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

NodeJS Basic Tutorial

NodeJS Express.js

NodeJS Buffer&URL;

NodeJS MySql

NodeJS MongoDB

NodeJS File (FS)

Other NodeJS

Node.js Append Content to File in FS

Node.js Appending Content to File

To append data to a file in Node.js, please use the Node FS appendFile() function for asynchronous file operations, or use the Node FS appendFileSync() function for synchronous file operations.

In this Node.js tutorial, we will learn

  • Syntax of appendFile() function

  • Syntax of appendFileSync() function

  • Example of appendFile() adding data to a file asynchronously

  • Example of appendFileSync() adding data to a file synchronously

 Syntax of appendFile()

fs.appendFile(filepath, data, options, callback_function);

The callback function is mandatory and will be called after the data is appended to the file.

 Syntax of appendFileSync()

fs.appendFileSync(filepath, data, options);

Parameter Description:

  • filepath [Required] Is a string used to specify the file path

  • data [Required] The content you want to append to the file

  • Options [Optional] Specify encoding/Mode/Flag

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

Example: Node.js uses appendFile() to asynchronously append data to a file

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

// Example Node.js program to append data to a file
var fs = require('fs'); 
 
var data = "\nLearn Node.js with the help of well-structured Node.js Tutorial."; 
 
// Append data to file
fs.appendFile('sample.txt', data, 'utf8', 
    // Callback function
    function(err) {  
        if (err) throw err; 
        // If there is no error
        console.log("Data appended to file successfully.") 
 });

Terminal Output

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

File before appending

// Example Node.js program to append data to a file
var fs = require('fs'); 
 
var data = "\nLearn Node.js with the help of well-structured Node.js Tutorial."; 
 
// Append data to file
fs.appendFileSync('sample.txt', data, 'utf8'); 
console.log("Data appended to file successfully.")

Terminal Output

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

File before appending

Welcome to www.oldtoolbag.com.

File appended

Welcome to www.oldtoolbag.com. 
Learn Node.js with the help of well-structured Node.js Tutorial.

Summary:

In this tutorial- Append to a file in Node.jsIn this tutorial, we have learned how to append data to Node.js files, using the appendFileSync() and appendFile() methods of the Node.js file system module, respectively, in instance Node.js programs.