The fs.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.
fs.writeFile( file, data, options, callback )
Parameters: This method accept four 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 fs.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’.
- callback: It is the function that would be called when the method is executed.
- err: It is an error that would be thrown if the operation fails.
Below examples illustrate the fs.writeFile() method in Node.js:
File written successfully The written has the following contents: This is a file containing a collection of books.
File written successfully The written has the following contents: This is a file containing a collection of movies.
- Nodejs | Automatic restart NodeJs server with nodemon
- Nodejs console.timeLog() Method
- Nodejs - Connect MongoDB with Node app using MongooseJS
- Cowsay in Nodejs using Requests library
- Nodejs | Web Crawling using Cheerio
- Web-Socket in NodeJS
- Signup Form Using Nodejs and MongoDB
- Dockerizing a simple Nodejs app
- Nodejs | DNS
- Encrypting Data in NodeJS
- Difference between NodeJS and AngularJS
- Nodejs | Jimp
- Nodejs – Connect Mysql with Node app
- Nodejs | DNS | setServers()
- NodeJS | Building simple REST API in express
- NodeJs - Handling invalid routes
- Nodejs | authentication using Passportjs and passport-local-mongoose
- Nodejs | GM charcoal() Function
- Nodejs | GM blur() Function
- Nodejs | GM sharpen() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.