fs.writeFile():
The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file, containing the specified content, will be created.
Syntax:
fs.writeFile(path, data, options, callback);
const fs = require("fs");
fs.writeFile(
"paper.txt",
"Hello world!",
err => {
if (err) throw err;
console.log("success");
}
);
Using buffer
fs.write(fd, buffer, offset, length, position, callback)
Using string
fs.write(fd, string, position, encoding, callback)
Parameters: The method accepts the following parameters as mentioned above and described below:
- fd: A file descriptor the value returned by opening the file using the fs.open() method. It contains an integer value.
- buffer: It contains the buffer type values like Buffer, TypedArray, and DataView.
- offset: It is an integer value that determines the part of the buffer to be written to the file.
- length: It is an integer value that specifies the number of bytes to write into the file.
- position: It is an integer value that holds the position that refers to the offset from the beginning of the file where the data is to be written.
- callback: It contains a callback function that receives an error and the number of bytes written to the file.
- string: Write a string to the file specified by fd.
- encoding: The default encoding value is UTF-8.
fs.writeFileSync():
Syntax:
fs.writeFileSync(path, data, options);
const fs = require("fs");
try {
fs.writeFileSync("mozahed.txt", "Mozahedul Islam is a well-known programmer");
} catch (err) {
if (err) throw err;
}
Post a Comment