Sometimes, we want to fix the writeFile ‘no such file or directory’ error in Node.js.
In this article, we’ll look at how to fix the writeFile ‘no such file or directory’ error in Node.js.
How to fix the writeFile ‘no such file or directory’ error in Node.js?
To fix the writeFile ‘no such file or directory’ error in Node.js, we can call mkdirp
to create the folder before we call writeFile
to make sure the directory we’re writing to exists.
For instance, we write
const mkdirp = require("mkdirp");
const fs = require("fs");
const writeFile = async (path, content) => {
await mkdirp(path);
fs.writeFileSync(path, content);
};
to call mkdirp
with the path
to create the folder as the path
if it doesn’t exist.
Then we call fs.writeFileSync
to write the file to the path
.
Conclusion
To fix the writeFile ‘no such file or directory’ error in Node.js, we can call mkdirp
to create the folder before we call writeFile
to make sure the directory we’re writing to exists.