In the post Writing a File in Node.js we saw how to use methods of fs module to write to a file. When you use writeFile() method it rewrites the file if file already exists. If you need to append to a file then fs module has methods to do that too.
How to append to a file in Node.js
In the fs module there are both synchronous and asynchronous methods to append to a file. Description is as given below.
- fs.appendFile()- This method asynchronously appends data to a file, creating the file if it does not yet exist. A callback function is provided which is called when the file append operation is completed.
- fs.appendFileSync- This method synchronously appends data to a file, creating the file if it does not yet exist.
- fsPromises.appendFile()- This method is in the fs.promises API which asynchronously appends data to a file, creating the file if it does not yet exist. Method returns a Promise object which is resolved with undefined upon success.
Using fs.appendFile()
Syntax of fs.appendFile() method is as given below.
fs.appendFile(path, data, options, callback)
The four parameters are described below-
- file- Path to the file where content has to be written or file descriptor (a number returned by opening the file using the open() method).
- data- Content to be written to the file. It can be of type string or Buffer.
- options- It specifies optional parameters that can be provided with write operation. Type can be either string or object.
Optional parameters are described below-
- encoding- A string value specifying the encoding of the file. Default is 'utf8'
- mode- An integer value specifying the file mode. Default is 0o666 which means both read and write.
- flag- Flag used in append operation. Default flag is 'a' which means open file for appending. The file is created if it does not exist.
- flush- If true, the underlying file descriptor is flushed prior to closing it. Default value is false.
- callback- A function that is called when the file operation completes. Takes one argument err which denotes the error that can be thrown if append operation fails.
fs.appendFile () Example
const fs = require('fs'); var os = require("os"); const path = require('path'); const content = 'This is a line added to the file' + os.EOL; fs.appendFile(path.join(__dirname, 'Hello.txt'), content, (err) => { if(err){ console.error(err); }else { console.log("Append operation completed"); } })
Here os.EOL
const of the 'os' module is used to add new line at the end.
Using fs.appendFileSync()
Syntax of fs.appendFileSync() method is as given below
fs.appendFileSync(path, data, options)
Description of parameters is similar to fs.appendFile()
fs.appendFileSync() Example
const fs = require('fs'); var os = require("os"); const path = require('path'); const content = 'This is a line added to the file' + os.EOL; fs.appendFileSync(path.join(__dirname, 'Hello.txt'), content); console.log("Append operation completed");
Using fsPromises.appendFile()
Syntax of fsPromises.appendFile() method is as given below
fsPromises.appendFile(path, data, options)
Description of parameters is similar to fs.appendFile() method as given above.
fsPromises.appendFile() example
const fs = require('fs'); const fspromises = fs.promises; var os = require("os"); const path = require('path'); // uses async/await const appendFile = async (filePath) => { try{ const content = 'This is a line added to the file' + os.EOL; await fspromises.appendFile(filePath, content); console.log("Append operation completed"); } catch(error){ console.error(err); } } // function call appendFile(path.join(__dirname, 'Hello.txt'));
That's all for this topic Appending a File in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!
Related Topics
You may also like-
No comments:
Post a Comment