我有一个函数可以根据发送给它的参数下载一个文件并将其保存在一个嵌套的目录结构中(例如:./somedir/a/b/c或./ somedir2 /一个/ d/b)中。我不能相信任何沿途的目录都已经创建好了,所以我需要让文件路径中的每个目录都被检查并创建(如果它不存在)。现在,我有一些完美适用于Node 0.4.x的代码,但是至少在Node 0.5.x的Windows版本(特别是在0.5.10上进行了测试)中出现了一些问题。为Node.js创建递归目录0.5.x
我对理解文件系统非常糟糕,所以如果有人能够弄清楚我怎样才能完成这项工作或者用其他类似的工具替代它,我将非常感激。目标是让代码在Unix和Windows以及Node 0.4.x和0.5.x上正常运行。
// automatically create directories if they do not exist at a path
function mkdirs(_path, mode, callback) {
var dirs = _path.split("/");
var walker = [dirs.shift()];
var walk = function (ds, acc, m, cb) {
if (ds.length > 0) {
var d = ds.shift();
acc.push(d);
var dir = acc.join("/");
fs.stat(dir, function (err, stat) {
if (err) {
// file does not exist
if (err.errno == 2) {
fs.mkdir(dir, m, function (erro) {
if (erro && erro.errno != 17) {
terminal.error(erro, "Failed to make " + dir);
return cb(new Error("Failed to make " + dir + "\n" + erro));
} else {
return walk(ds, acc, m, cb);
}
});
} else {
return cb(err);
}
} else {
if (stat.isDirectory()) {
return walk(ds, acc, m, cb);
} else {
return cb(new Error("Failed to mkdir " + dir + ": File exists\n"));
}
}
});
} else {
return cb();
}
};
return walk(dirs, walker, mode, callback);
};
实例应用:
mkdirs('/path/to/file/directory/', 0777, function(err){
编辑:更新节点0.8.4(在CoffeeScript中):
#
# Function mkdirs
# Ensures all directories in a path exist by creating those that don't
# @params
# path: string of the path to create (directories only, no files!)
# mode: the integer permission level
# callback: the callback to be used when complete
# @callback
# an error object or false
#
mkdirs = (path, mode, callback) ->
tryDirectory = (dir, cb) ->
fs.stat dir, (err, stat) ->
if err #the file doesn't exist, try one stage earlier then create
if err.errno is 2 or err.errno is 32 or err.errno is 34
if dir.lastIndexOf("/") is dir.indexOf("/") #only slash remaining is initial slash
#should only be triggered when path is '/' in Unix, or 'C:/' in Windows
cb new Error("notfound")
else
tryDirectory dir.substr(0, dir.lastIndexOf("/")), (err) ->
if err #error, return
cb err
else #make this directory
fs.mkdir dir, mode, (error) ->
if error and error.errno isnt 17
cb new Error("failed")
else
cb()
else #unkown error
cb err
else
if stat.isDirectory() #directory exists, no need to check previous directories
cb()
else #file exists at location, cannot make folder
cb new Error("exists")
path = (if path.indexOf("\\") >= 0 then path.replace("\\", "/") else path) #change windows slashes to unix
path = path.substr(0, path.length - 1) if path.substr(path.length - 1) is "/" #remove trailing slash
tryDirectory path, callback
我已经使用不同分束逻辑确定如果操作系统是Windows'变种窗口= _path.indexOf( '\\')>尝试= 0;',但我仍然遇到ENOENT错误。从我所知道的情况来看,fs.stat在errno 32中返回一个错误,导致代码失败。 – geoffreak
在做了一些更多的研究之后,似乎fs.stat有些问题,所以我提交了一个关于github的问题(https://github.com/joyent/node/issues/1927)。 – geoffreak