fs.writeFile()
is an asynchronous method for writing data in files of any type.
fs.writeFile(File_Path, Data , callback());
File_Path
: A string representing the full path of the file with the name.Data
: Information that has to be written in the file.Callback
: A function with an error parameter.Let’s try to write to a file and print its data in the console.
Take a look at the code below. We have two files:
demo.txt
: an empty text file.
index.js
: node code to write data in the file ‘demo.txt’.
const fs = require('fs');fs.writeFile('demo.txt', 'hello Ayush' ,(err)=> {if(err){console.log('error',err);}console.log('DONE');})fs.readFile('demo.txt' ,(err,data)=> {if(err){console.log('error',err);}console.log(data.toString());})
The code above is a simple example of how to use fs.writeFile()
.
In line 1, we import the fs
module and create an object of it.
In line 3, we use fs.writeFile()
to write to a file. We provide the file path and a callback function.
In line 4, we have an if
condition. If the write operation fails it will return err
and you can use err
to check the cause for failure.
In line 5, we print the err
if it fails to write to the file.
In line 10, we use readFile()
to check if we have successfully done the write operation and print the file content in the console.
Click on Run. The output is ‘hello Ayush’, which was written by the function fs.writeFile()
file.
Check line 3, which indicates we have successfully completed the task to write a file in node.
You can change the string ‘hello Ayush’ in the function fs.writeFile()
file and see the output after executing the code.