The fsPromises.writeFile() method asynchronously writes data to a file and replaces the file by default, with optional settings to control its behavior.
- Writes data to a file asynchronously using Promises.
- Replaces the file if it already exists.
- Supports an options parameter to customize behavior.
- Resolves the Promise with no value on successful completion.
Syntax
fsPromises.writeFile( file, data, options )- file: String, Buffer, URL, or file descriptor indicating the file path where data will be written
- data: String, Buffer, TypedArray, or DataView to be written to the file
- options: String or object to control write behavior (encoding, mode, and flag)
- encoding: Specifies file encoding, default is
utf8 - mode: Specifies file permissions, default is
0o666 - flag: Specifies the write flag, default is
w - Returns: Promise that resolves on successful completion
Below examples illustrate the fsPromises.writeFile() method in Node.js:
[Example 1]: Create and write content into movies.txt asynchronously using fsPromises.writeFile() in Node.js
// Node.js program to demonstrate the
// fsPromises.writeFile() method
// Import the filesystem module
const fs = require('fs');
const fsPromises = require('fs').promises;
let data = "This is a file containing"
+ " a collection of movies.";
(async function main() {
try {
await fsPromises.writeFile(
"movies.txt", data)
console.log("File written successfully");
console.log("The written file has"
+ " the following contents:");
console.log("" +
fs.readFileSync("./movies.txt"));
} catch (err) {
console.error(err);
}
})();
Output:
File written successfully
The written file has the following contents:
This is a file containing a collection of movies.
[Example 2]: Write data to a file asynchronously using fsPromises.writeFile() in Node.js
// Node.js program to demonstrate the
// fsPromises.writeFile() method
// Import the filesystem module
const fs = require('fs');
const fsPromises = require('fs').promises;
let data = "This is a file containing"
+ " a collection of books.";
(async function main() {
try {
await fsPromises.writeFile(
"books.txt", data, {
encoding: "utf8",
flag: "w",
mode: 0o666
});
console.log("File written successfully\n");
console.log("The written has the "
+ "following contents:");
console.log("" +
fs.readFileSync("books.txt"));
}
catch (err) {
console.error(err);
}
})();
Output:
File written successfully
The written has the following contents:
This is a file containing a collection of books.
Reference: https://nodejs.org/api/fs.html#fs_fspromises_writefile_file_data_options