I need to write file to the following path:
fs.writeFile('/folder1/folder2/file.txt', 'content', function () {
});
But '/folder1/folder2' path may not exists. So I get the following error:
message=ENOENT, open /folder1/folder2/file.txt
How can I write content to that path?
Use mkdirp in combination with path.dirname first.
var mkdirp = require("mkdirp")
var fs = require("fs")
var getDirName = require("path").dirname
function writeFile (path, contents, cb) {
mkdirp(getDirName(path), function (err) {
if (err) return cb(err)
fs.writeFile(path, contents, cb)
})
}
If the whole path already exists, mkdirp is a noop. Otherwise it creates all missing directories for you.
This module does what you want: https://npmjs.org/package/writefile . Got it when googling for "writefile mkdirp". This module returns a promise instead of taking a callback, so be sure to read some introduction to promises first. It might actually complicate things for you.
The function I gave works in any case.
You can use
fs.stat('/folder1/folder2', function(err, stats){ ... });
stats is a fs.Stats type of object, you may check stats.isDirectory(). Depending on the examination of err and stats you can do nothing, fs.mkdir( ... ) or throw an error.
Update: Fixed the commas in the code.