Node.js 0.5.x的recursion目录创build

Node.js 0.5.x的recursion目录创build,第1张

概述Node.js 0.5.x的recursion目录创build

我有一个函数,下载一个文件,并根据发送给它的参数(如:./somedir/a/b/c或./somedir2/a/d/b)将其保存在一个嵌套的目录结构中。 我不能相信沿途的任何目录已经创build,所以我需要沿着文件path的每个目录检查和创build,如果它不存在。 现在,我有一些代码完全适用于Node 0.4.x,但是至less在Node 0.5.x的windows版本中(特别是在0.5.10上testing过的)有些问题。

我对理解文件系统非常糟糕,所以如果有人能够弄清楚我怎样才能完成这个工作,或者用其他类似的工具代替它,我将非常感激。 目标是让代码在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 existsn")); } } }); } else { return cb(); } }; return walk(dirs,walker,callback); };

用法示例:

mkdirs('/path/to/file/directory/',0777,function(err){

编辑:节点0.8.x更新(在CoffeeScript中):

了解来自多个进程的并发文件写入

linux设备驱动文件 *** 作:有可能有竞争条件吗?

用C中的零覆盖整个文件的最快方法是什么?

如何从linux系统caching中驱逐文件?

摆脱基于文件的通信

# # 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

使用C读取大文件(大于4GB)使用读取function,导致问题

linux中无缓冲的I / O

我如何select用户删除文件夹中的所有文件(但没有子目录)?

为什么fprintf不直接写入文件,除非使用fflush()?

当我尝试打开删除挂起的文件时,为什么windows返回ERROR_ACCESS_DENIED

看看node-fs( https://npmJs.org/package/node-fs )。

node-fs是原始nodeJs fs库的扩展,提供了新的功能,例如递归目录创建。

function mkdir(path,root) { var dirs = path.split('/'),dir = dirs.shift(),root = (root || '') + dir + '/'; try { fs.mkdirsync(root); } catch (e) { //dir wasn't made,something went wrong if(!fs.statSync(root).isDirectory()) throw new Error(e); } return !dirs.length || mkdir(dirs.join('/'),root); }

用法:

var fs = require('fs'); mkdir('parent/child/grandchild');

我有一个网站,允许用户将他们的照片上传到自己的文件夹。 我无法找到一个好的开源模块递归创建目录,所以我实现了一个。 https://github.com/samxxu/ensureDir ,可以通过安装

$ npm install ensureDir

以下是完整的源代码:

var path = require('path'); var fs = require('fs'); /** * ensure a directory exists,create it recursively if not. * * @param dir The directory you want to ensure it exists * @param mode Refer to fs.mkdir() * @param callback */ module.exports = function ensureDir(dir,callback) { if (mode && typeof mode === 'function') { callback = mode; mode = null; } mode = mode || 0777 & (~process.umask()); callback = callback || function () { }; _ensureDir(dir,callback); } function _ensureDir(dir,callback) { var existsFunction = fs.exists || path.exists; existsFunction(dir,function (exists) { if (exists) return callback(null); var current = path.resolve(dir); var parent = path.dirname(current); _ensureDir(parent,function (err) { if (err) return callback(err); fs.mkdir(current,function (err) { if (err) return callback(err); callback(); }); }); }); }

在geoffreak的基础上做一个同步版本。

感谢geoffreak。

function mkdirs(path,callback){ var path = path.indexOf('\') >= 0 ? path.replace(/\/g,'/') : path;//change windows slashes to unix if (path.substr(path.length - 1) == '/') { //remove trailing slash path = path.substr(0,path.length - 1); } console.log('path is:' + path ); function tryDirectory(dir,cb){ console.log('path is:' + dir ); var stat ; try { stat = fs.statSync(dir) ; // the file exist if (stat.isDirectory()) { //directory exists,no need to check prevIoUs directorIEs cb(); } else { //file exists at location,cannot make folder return cb(new Error('exists')); } } catch(err) { if (err) { //the file doesn't exist,try one stage earlIEr then create console.log('Failed to get stat of ' + dir + ',errno is :' + err.errno); if (err.errno == 2 || err.errno == 32 || err.errno == 34 ) { //if (dir.lastIndexOf('/') == 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')); //} if (dir.length < 2) { cb(new Error('invalID_path')); } else { // try one stage earlIEr then create tryDirectory(dir.substr(0,dir.lastIndexOf('/')),function(err){ if (err) { //error,return cb(err); } else { //make this directory try { fs.mkdirsync(dir,mode); console.log('make dir ok,dir:' + dir); cb(); } catch (error) { if (error && error.errno != 17 ) { console.log("Failed to make " + dir); return cb(new Error('Failed')); } } } }); } } else { //unkown error console.log(util.inspect(err,true)); cb(err); } } } } tryDirectory(path,callback); };

回答我自己的问题感觉很傻,但我似乎已经想通了。 只要确保使用基于__dirname的相对路径来确保跨平台兼容性。 如果有人发现任何问题,请让我知道。 我已经在windows(0.5.10)和Mac(0.4.12)上测试过它。

// automatically create directorIEs if they do not exist at a path function mkdirs(path,callback){ var path = path.indexOf('\') >= 0 ? path.replace('\',path.length - 1); } function tryDirectory(dir,cb){ fs.stat(dir,stat) { if (err) { //the file doesn't exist,try one stage earlIEr then create if (err.errno == 2 || err.errno == 32) { if (dir.lastIndexOf('/') == 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,return cb(err); } else { //make this directory fs.mkdir(dir,function (error) { if (error && error.errno != 17) { console.log("Failed to make " + dir); return cb(new Error('Failed')); } else { cb(); } }); } }); } } else { //unkown error console.log(util.inspect(err,true)); cb(err); } } else { if (stat.isDirectory()) { //directory exists,cannot make folder return cb(new Error('exists')); } } }); } tryDirectory(path,callback); };

这也是有效的。 迭代的,非递归的,算法。

“`

function mkdirs(path) { var dirs = path.split('/'); var prevDir = dirs.splice(0,1)+"/"; while(dirs.length > 0) { var curDir = prevDir + dirs.splice(0,1); if (! fs.existsSync(curDir) ) { fs.mkdirsync(curDir); } prevDir = curDir + '/'; } }

“`

必须有一个非常小的版本,这是一个部署服务器,这是尽可能美丽,因为我可以得到它。

function mkdirs(file){ var dirs,paths=[]; dirs = file.split('/'); while(dirs.length>1){ paths.push(dirs.shift()); var tmp = paths.join('/'); if(!fs.existsSync('/'+tmp )) fs.mkdirsync('/'+tmp); } }

总结

以上是内存溢出为你收集整理的Node.js 0.5.x的recursion目录创build全部内容,希望文章能够帮你解决Node.js 0.5.x的recursion目录创build所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1157544.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-01
下一篇 2022-06-01

发表评论

登录后才能评论

评论列表(0条)

保存