How to append a file in Node.js
Problem statement
Implement an fs.appendFile() function that asynchronously appends data to the end of the test.txt file.
The fs module
The fs module is a built-in global Node.js module that exposes an API to access, manipulate, and interact with the file system.
Syntax
fs.appendFile(path, data)
Parameters
path: This is a file path.data: This is the data to be written to the file.
Example
Let’s look at the code below:
const fs = require("fs").promises;const appendFile = async (path, data) => {try {await fs.appendFile(path, data);} catch (error) {console.error(error);}};appendFile("./test.txt", "appending another hello world");
Explanation
-
Line 1: We load the
fsmodule to read a file. The module system uses therequirefunction to load in a module and access its contents. We usepromiseobjects forasync/awaitkeywords instead of callbacks to handle asynchronicity. -
Line 2: We store an async
pathwhere the file is located and thedatathat we need to append in the text file. -
Line 3–8: We use a
tryandcatchand append the data in the file. -
Line 9: We set a path of a file and data as a parameter in the
appendFilefunction.
Free Resources