Implement an fs.appendFile()
function that asynchronously appends data to the end of the test.txt
file.
fs
moduleThe fs
module is a built-in global Node.js module that exposes an API to access, manipulate, and interact with the file system.
fs.appendFile(path, data)
path
: This is a file path.data
: This is the data to be written to the file.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");
Line 1: We load the fs
module to read a file. The module system uses the require
function to load in a module and access its contents. We use promise
objects for async/await
keywords instead of callbacks to handle asynchronicity.
Line 2: We store an async path
where the file is located and the data
that we need to append in the text file.
Line 3–8: We use a try
and catch
and append the data in the file.
Line 9: We set a path of a file and data as a parameter in the appendFile
function.
Free Resources