Sometimes, we want to check if writeFileSync successfully wrote the file with Node.js and JavaScript.
In this article, we’ll look at how to check if writeFileSync successfully wrote the file with Node.js and JavaScript.
How to check if writeFileSync successfully wrote the file with Node.js and JavaScript?
To check if writeFileSync successfully wrote the file with Node.js and JavaScript, we use the exists
method.
For instance, we write
fs.exists(file, (exists) => {
if (exists) {
fs.writeFile(file, content, "utf-8", (err) => {
if (err) {
console.log("failed to save");
} else {
console.log("succeeded in saving");
}
});
} else {
console.log("file does not exist");
}
});
to call fs.exists
with the file
path string to check if the file at the path exists.
The callback has the exists
parameter which is true
is the file exists at the path.
We call fs.writeFile
when exists
is true
, which means the file exists.
Conclusion
To check if writeFileSync successfully wrote the file with Node.js and JavaScript, we use the exists
method.