NodeJS异步、同步 创建多层文件夹
同步:
//创建多层文件夹 同步 function mkdirsSync(dirpath, mode) { if (!fs.existsSync(dirpath)) { var pathtmp; dirpath.split(path.sep).forEach(function(dirname) { if (pathtmp) { pathtmp = path.join(pathtmp, dirname); } else { pathtmp = dirname; } if (!fs.existsSync(pathtmp)) { if (!fs.mkdirSync(pathtmp, mode)) { return false; } } }); } return true; }
异步:
//创建多层文件夹 异步 function mkdirs(dirpath, mode, callback) { callback = callback || function() {}; fs.exists(dirpath, function(exitsmain) { if (!exitsmain) { //目录不存在 var pathtmp; var pathlist = dirpath.split(path.sep); var pathlistlength = pathlist.length; var pathlistlengthseed = 0; mkdir_auto_next(mode, pathlist, pathlist.length, function(callresult) { if (callresult) { callback(true); } else { callback(false); } }); } else { callback(true); } }); } // 异步文件夹创建 递归方法 function mkdir_auto_next(mode, pathlist, pathlistlength, callback, pathlistlengthseed, pathtmp) { callback = callback || function() {}; if (pathlistlength > 0) { if (!pathlistlengthseed) { pathlistlengthseed = 0; } if (pathlistlengthseed >= pathlistlength) { callback(true); } else { if (pathtmp) { pathtmp = path.join(pathtmp, pathlist[pathlistlengthseed]); } else { pathtmp = pathlist[pathlistlengthseed]; } fs.exists(pathtmp, function(exists) { if (!exists) { fs.mkdir(pathtmp, mode, function(isok) { if (!isok) { mkdir_auto_next(mode, pathlist, pathlistlength, function(callresult) { callback(callresult); }, pathlistlengthseed + 1, pathtmp); } else { callback(false); } }); } else { mkdir_auto_next(mode, pathlist, pathlistlength, function(callresult) { callback(callresult); }, pathlistlengthseed + 1, pathtmp); } }); } } else { callback(true); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。