How do I use nodejs to write a file, if the file is in a directory that may or may not exist?
It's kind of similar to this question:
node.js Write file with directories?
Only I need a solution that creates the file while node-fs only makes directories.
From FileUtils:
Modify the functions to satisfy yours needs! But seriously, use a module instead of writing your own!
createDirectory(): Creates a directory. If any of the previous directories that form the path don't exist, they are created. Default permissions: 0777.
File.prototype.createDirectory = function (cb){
if (cb) cb = cb.bind (this);
if (!this._path){
if (cb) cb (NULL_PATH_ERROR, false);
return;
}
if (!canWriteSM (this._usablePath)){
if (cb) cb (SECURITY_WRITE_ERROR, false);
return;
}
var mkdirDeep = function (path, cb){
path.exists (function (exists){
if (exists) return cb (null, false);
FS.mkdir (path.getPath (), function (error){
if (!error) return cb (null, true);
var parent = path.getParentFile ();
if (parent === null) return cb (null, false);
mkdirDeep (parent, function (error, created){
if (created){
FS.mkdir (path.getPath (), function (error){
cb (error, !error);
});
}else{
parent.exists (function (exists){
if (!exists) return cb (null, false);
FS.mkdir (path.getPath (), function (error){
cb (error, !error);
});
});
}
});
});
});
};
mkdirDeep (this.getAbsoluteFile (), function (error, created){
if (cb) cb (error, created);
});
};
createNewFile(): Creates a new file. Default permissions: 0666.
File.prototype.createNewFile = function (cb){
if (cb) cb = cb.bind (this);
if (!this._path){
if (cb) cb (NULL_PATH_ERROR, false);
return;
}
if (!canWriteSM (this._usablePath)){
if (cb) cb (SECURITY_WRITE_ERROR, false);
return;
}
var path = this._usablePath;
PATH.exists (path, function (exists){
if (exists){
if (cb) cb (null, false);
}else{
var s = FS.createWriteStream (path);
s.on ("error", function (error){
if (cb) cb (error, false);
});
s.on ("close", function (){
if (cb) cb (null, true);
});
s.end ();
}
});
};
I just wrote this as answer to How to write file if parent folder dosen't exists? . Might be useful for someone stumbling upon this in Google:
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)
})
}
You can just use something like createWriteStream
.
It will just create the file if it didn't exist.
you can use https://github.com/douzi8/file-system
var file = require('file-system');
file.mkdir('1/2/3/4/5', [mode], function(err) {});