Sometimes, we want to write file if parent folder doesn’t exist with Node.js.
In this article, we’ll look at how to write file if parent folder doesn’t exist with Node.js.
How to write file if parent folder doesn’t exist with Node.js?
To write file if parent folder doesn’t exist with Node.js, we can call mkdir
to create the folder before creating the file in the folder.
For instance, we write
const fs = require('fs');
const getDirName = require('path').dirname;
fs.mkdir(getDirName(path), {
recursive: true
}, (err) => {
if (err) return cb(err);
fs.writeFile(path, contents, (err) => {
//...
});
});
to call fs.mkdir
with the folder path we want to create and an object that has recursive
set to true
to create the folder event if the parent folder doesn’t exist.
Then in the mkdir
callback, we call writeFile
to write the file to the given path
.
Conclusion
To write file if parent folder doesn’t exist with Node.js, we can call mkdir
to create the folder before creating the file in the folder.