Open In App

Node.js | fs.appendFileSync() Function

The fs.appendFileSync() method is used to synchronously append the given data to a file. A new file is created if it does not exist. The optional options parameter can be used to modify the behavior of the operation.

Syntax:



fs.appendFileSync( path, data, [options])

Parameters:

This method accepts three parameters as mentioned above and described below:



Below examples illustrate the fs.appendFileSync() method in Node.js:

Example 1: This example shows the appending of the given text to a file.




// Node.js program to demonstrate the
// fs.appendFileSync() method
 
// Import the filesystem module
const fs = require('fs');
 
// Get the file contents before the append operation
console.log("\nFile Contents of file before append:",
  fs.readFileSync("example_file.txt", "utf8"));
 
fs.appendFileSync("example_file.txt", " - Geeks For Geeks");
 
// Get the file contents after the append operation
console.log("\nFile Contents of file after append:",
       fs.readFileSync("example_file.txt", "utf8"));

Output:

File Contents of file before append: Hello
File Contents of file after append: Hello - Geeks For Geeks

Example 2:

This example shows the usage of the optional parameters to change the file encoding and flag of the operation. The “w” flag replaces the contents of the file instead of appending to it.




// Node.js program to demonstrate the
// fs.appendFileSync() method
 
// Import the filesystem module
const fs = require('fs');
 
// Get the file contents before the append operation
console.log("\nFile Contents of file before append:",
  fs.readFileSync("example_file.txt", "utf8"));
 
// Append to the file using optional parameters
fs.appendFileSync("example_file.txt",
  "This is the appended text",
  { encoding: "utf8", flag: "w" }
);
 
// Get the file contents after the append operation
console.log("\nFile Contents of file after append:",
       fs.readFileSync("example_file.txt", "utf8"));

Output:

File Contents of file before append: This is a test file
File Contents of file after append: This is the appended text

Reference:

https://nodejs.org/api/fs.html#fs_fs_appendfilesync_path_data_options


Article Tags :