如果文件位于可能存在或可能不存在的目录中,我如何使用 nodejs 编写文件?
这有点类似于这个问题:
node.js Write file with directories?
只有我需要一个创建文件的解决方案,而 node-fs 只创建目录。
最佳答案
来自 FileUtils :
修改功能以满足您的需求!但说真的,使用模块而不是编写自己的模块!
createDirectory() : 创建一个目录。如果形成路径的任何先前目录不存在,则会创建它们。默认权限: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() : 创建一个新文件。默认权限: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 ();
}
});
};
关于node.js递归写入文件目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10731899/