To write file if parent folder doesn’t exist with Node.js, we use the fs-extra
module.
For instance, we write
const fs = require("fs-extra");
const file = "/tmp/this/path/does/not/exist/file.txt";
fs.outputFile(file, "hello!", (err) => {
console.log(err);
fs.readFile(file, "utf8", (err, data) => {
console.log(data);
});
});
to call the outputFile
method to write 'hello!'
to the file
path.
And then we call readFile
to read the file
path in the outputFile
callback.