我有一个下载文件的功能,并将其保存在基于发送给它的参数的嵌套目录结构中(例如:./somedir/a/b/c或./somedir2/a/d/b).我不能相信任何目录一直被创建,所以我需要沿文件路径检查和创建每个目录,如果它不存在.现在,我有一些代码可以很好地适用于Node 0.4.x,但至少在
Windows版本的Node 0.5.x中有一些破坏(具体在0.5.10上测试).
理解文件系统是非常糟糕的,所以如果有人能弄清楚我能做什么工作,或者用其他类似的东西替换它,我将非常感激.目标是在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,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,cb); } }); } else { return cb(err); } } else { if (stat.isDirectory()) { return walk(ds,cb); } else { return cb(new Error("Failed to mkdir " + dir + ": File exists\n")); } } }); } else { return cb(); } }; return walk(dirs,walker,callback); };
使用示例
mkdirs('/path/to/file/directory/',0777,function(err){
编辑:节点0.8.x的更新(在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,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,(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
看一下node-fs(
https://npmjs.org/package/node-fs).
原文链接:https://www.f2er.com/windows/363884.htmlnode-fs是原始nodejs fs库的扩展,提供了新的功能,如递归目录创建.