The Wayback Machine - https://web.archive.org/web/20240901053133/https://www.geeksforgeeks.org/node-js-fs-appendfile-function/
Open In App

Node fs.appendFile() Function

Last Updated : 15 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Syntax:

fs.appendFile( path, data[, options], callback )

Parameters:

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

  • path: It is a String, Buffer, URL or number that denotes the source filename or file descriptor that will be appended to.
  • data: It is a String or Buffer that denotes the data that has to be appended.
  • options: It is an string or an object that can be used to specify optional parameters that will affect the output. It has three optional parameters:
    • encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.
    • mode: It is an integer which specifies the file mode. The default value is ‘0o666’.
    • flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’.
  • callback: It is a function that would be called when the method is executed.
    • err: It is an error that would be thrown if the method fails.

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

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

Javascript




// Node.js program to demonstrate the
// fs.appendFile() 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.appendFile("example_file.txt", "World", (err) => {
    if (err) {
        console.log(err);
    }
    else {
        // 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: HelloWorld

Example 2: This example shows the usage of the optional parameters to change the file encoding, mode, and flag of the operation.

Javascript




// Node.js program to demonstrate the
// fs.appendFile() 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.appendFile("example_file.txt", " - GeeksForGeeks",
    { encoding: "latin1", mode: 0o666, flag: "a" },
    (err) => {
        if (err) {
            console.log(err);
        }
        else {
            // 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 a test file - GeeksForGeek

We have a Cheat Sheet on Node fs modules where we covered all the fs methods to check those please go through Node File System Complete Reference article



Previous Article
Next Article

Similar Reads

Node.js fsPromises.appendFile() Function
The fsPromises.appendFile() method is used to asynchronously append the given data to a file. A new file is created if it does not exist. The options parameter can be used to modify the behavior of the operation. Syntax: fsPromises.appendFile( path, data, options ) Parameters: This method accepts three parameters as mentioned above and described be
2 min read
Node.js fs.promises.appendFile() Method
The fs.promises.appendFile() method of File System module in Node.js is used to interact with the hard disk of the user's computer. The appendFile() method is used to append new data into the existing file or if the file does not exist then file is created first and after that given data is appended to it. The fs.promises.appendFile() method return
4 min read
Node.js filehandle.appendFile() Method
The filehandle.appendFile() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The appendFile() method is used to asynchronously append new data in the existing file or if the file does not exist then the file is created first and after that given data i
3 min read
How to operate callback based fs.appendFile() method with promises in Node.js ?
The fs.appendFile() method is defined in the File System module of Node.js. The File System module is basically to interact with the hard disk of the user’s computer. The appendFile() method is used to append new data in the existing file or if the file does not exist then the file is created first and after that given data is appended to it. The f
4 min read
What are the advantages of synchronous function over asynchronous function in Node.js ?
Node.js furnishes us with an inbuilt fs (File System) module for different documents taking care of tasks like reading a record, composing a document, erasing a document, and so on. fs module can be introduced utilizing the underneath explanation: Syntax: npm introduce fs --save Note: The npm in the above order represents the hub bundle supervisor
5 min read
Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
Encountering the error message ‘node’ is not recognized as an internal or external command after installing Node.js can be frustrating, especially when you’re eager to start working on your project. This error usually means that your system cannot find the Node.js executable because the path to it is not set correctly in your system's environment v
2 min read
Node.js slice() function
The slice() function is a string function of Node.js which is used to extract sub-string from a string. Syntax: string.slice( start, end ) Parameters: This function uses three parameters as mentioned above and described below: string: It holds the string content. The substring is extracted from this string.start: This parameter holds the starting i
1 min read
Node.js crypto.scryptSync( ) Function
The crypto.scryptSync() is an inbuilt function which Provides a synchronous scrypt implementation in Node.js. scrypt is a password-based key derivation function. It is intended to be costly computationally plus memory-wise. So, the brute-force attacks are made unsuccessful. Syntax: crypto.scryptSync(password, salt, keylen[, options]) Parameter: Thi
3 min read
Node.js console.log() Function
The console.log() function from console class of Node.js is used to display the messages on the console. It prints to stdout with newline. Syntax: console.log( [data][, ...] ) Parameter: This function contains multiple parameters which are to be printed. Return type: The function returns the passed parameters. Below program demonstrates the working
1 min read
Node.js indexOf() function
The indexOf() function is a string function from Node.js which is used to find a string with another string. Syntax: str1.indexOf( str2 ) Parameter: This function uses two parameters as mentioned above and described below: str1: It holds the string content where another string is to be searched.str2: It holds the search string. Return Value: The fu
1 min read
Node.js trim() function
The trim() function is a string function of Node.js which is used to remove white spaces from the string. Syntax: string.trim() Parameter: This function does not accept any parameter. Return Value: The function returns the string without white spaces. The below programs demonstrate the working of trim() function: Program 1: C/C++ Code function trim
1 min read
Node.js split() function
The split() function is a string function of Node.js which is used to split strings into sub-strings. This function returns the output in array form. Syntax: string.split( separator ) Parameters: This function accepts a single parameter separator which holds the character to split the string. Return Value: The function returns the split string and
1 min read
Node.js substr() function
The substr() function is a string function of Node.js which is used to extract sub-string from the given string. Syntax: string.substr(index, length) Parameters: This function accepts two parameters as mentioned above and described below: index: This parameter holds the starting index of the specified sub-string.length: This parameter holds the len
1 min read
Node.js console.warn() Function
The console.warn() function from console class of Node.js is used to display the warning messages on the console. It prints to stderr with newline. Note: This function is an alias of console.error() function. Syntax: console.warn( [data][, ...args] ) Parameter: This function can contains multiple parameters. The first parameter is used for the prim
1 min read
Node.js console.error() Function
The console.error() function from the console class of Node.js is used to display an error message on the console. It prints to stderr with a newline. Syntax: console.error([data][, ...args]) Parameter: This function can contain multiple parameters. The first parameter is used for the primary message and other parameters are used for substitution v
1 min read
Node.js push() function
push() is an array function from Node.js that is used to add elements to the end of an array. Syntax: array_name.push(element) Parameter: This function takes a parameter that has to be added to the array. It can take multiple elements also. Return type: The function returns the array after adding the element. The program below demonstrates the work
1 min read
Node.js pop() function
pop() is an array function from Node.js that is used to remove elements from the end of an array. Syntax: array_name.pop() Parameter: This function does not take any parameter. Return type: The function returns the array. The program below demonstrates the working of the function: Example 1: C/C++ Code function POP() { arr.pop(); console.log(arr);
1 min read
Node.js shift() function
shift() is an array function from Node.js that is used to delete elements from the front of an array. Syntax: array_name.shift() Parameter: This function does not take any parameter. Return type: The function returns the array after deleting the element. The program below demonstrates the working of the function: Program 1: C/C++ Code function shif
1 min read
Node.js unshift() function
unshift() is an array function from Node.js that is used to insert elements to the front of an array. Syntax: array_name.unshift(element) Parameter: This function takes a parameter that has to be added to the array. It can take multiple elements also as parameters. Return type: The function returns the array after adding the element. The program be
1 min read
Node.js join() function
join() is an array function from Node.js that is used to return a string from the array. Syntax: array_name.join(parameter) Parameter: This function takes a single parameter as per which the join operation has to be performed. Return type: The function returns the string. The program below demonstrates the working of the function: Example 1: C/C++
1 min read
Node.js sort() function
sort() is an array function from Node.js that is used to sort a given array. Syntax: array_name.sort() Parameter: This function does not take any parameter. Return type: The function returns the sorted array. The program below demonstrates the working of the function: Program 1: C/C++ Code function sortDemo() { arr.sort() console.log(arr); } const
1 min read
Node.js GM drawLine() Function
The drawLine() function is an inbuilt function in the GraphicsMagick library which is used to draw the line with specified coordinates. The function returns the true value of success. Syntax: drawLine( x0, y0, x1, y1 ) Parameters: This function accepts four parameters as mentioned above and described below:. x0: This parameter stores the x-coordina
2 min read
Node.js GM drawArc() Function
The drawArc() function is an inbuilt function in the GraphicsMagick library which is used to draw an arc with specified coordinates. The function returns the true value of success. Syntax: drawArc( x0, y0, x1, y1, r0, r1 ) Parameters: This function accepts six parameters as mentioned above and described below:. x0: This parameter stores the value o
2 min read
Node.js GM drawPolyline() Function
The drawPolyline() function is an inbuilt function in the GraphicsMagick library which is used to draw polylines with specified coordinates. The function returns the true value of success. Syntax: drawPolyline( [x0, y0], ..., [xn, yn] ) Parameters: This function accepts the array of x and y coordinates. Return Value: This function returns the Graph
1 min read
Node.js GM drawBezier() Function
The drawBezier() function is an inbuilt function in the GraphicsMagick library which is used to draw the Bezier curve with specified coordinates. The function returns the true value of success. Syntax: drawBezier( [x0, y0], ..., [xn, yn] ) Parameters: This function accepts the array of points having x and y coordinates. Return Value: This function
1 min read