JavaScript has a package named “File System”, which lets the user work with files. In this package, there is a function named “writeFile”, whose sole purpose is to write data to a file specified within its path.
The writeFile() Method From “fs” Package
As mentioned above, the writeFile method is a part of the “fs” package, and to use this function, you need to include the “fs” package in your JavaScript application. To better understand the working of this writeFile(), take a look at its syntax below:
In this syntax:
- pathofFile: Specifies the exact path to the file in which data is to be written
- dataToWrite: The data that is to be written
- callbackFunction: The callback function to be executed in the case of an error while writing data to the file
Example: Writing Text Into a File Using writeFile() method
The first step to use the writeFile() function for writing data is to include the File System package in our program with the help of the following line:
The require keyword tells the compiler that you need to link the following package with this application. After that, simply use the variable “fs” with a dot operator to access the methods included in the file system package. After that, define the data that to write in a variable like:
After that, simply use the writeFile() method using the following lines:
if (err) {
console.error(err);
return;
}
In this above code snippet:
- The first argument specifies the location of the file, which in this case is placed in the folder as my program
- Second argument takes in the variable stringToWrite, which contains the data
- The third argument is a callback function with a variable err, that will be displayed onto the
terminal when an error occurs.
The complete code snippet will be as:
const stringToWrite = "HELLO I AM WRITTEN TO THE FILE";
fs.writeFile("./test.txt", stringToWrite, (err) => {
if (err) {
console.error(err);
return;
}
});
console.log("Data has been Written");
As for the test.txt file:
It is clear from the screenshot that currently, the file is empty.
Upon executing the above code, the following prompt is displayed on the terminal:
And inside the “test.txt” file, it shows:
From the above screenshot, it is clear that the data was written to the file test.txt
Conclusion
JavaScript includes a package named as “File System”, which is used to work with files. This package contains a method named as writeFile(), which is used to write data to a file specified in its argument. To use this method, the first thing is to include the package “fs” into the program by using a required keyword. This article has explained the process of writing data to a file through writeFile() with the help of an example.