The fsPromises.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method.
The Promise will be resolved with no arguments upon success.
fsPromises.writeFile( file, data, options )
Parameters: This method accepts three parameters as mentioned above and described below:
- file: It is a string, Buffer, URL or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similar to fsPromises.write() method.
- data: It is a string, Buffer, TypedArray or DataView that will be written to the file.
- options: It is an string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:
- encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.
- mode: It is an integer value that specifies the file mode. The default value is 0o666.
- flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’.
Return Value: This method returns a Promise.
Below examples illustrate the fsPromises.writeFile() method in Node.js:
File written successfully The written file has the following contents: This is a file containing a collection of movies.
File written successfully The written has the following contents: This is a file containing a collection of books.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.