纯异步nodejs文件夹(目录)复制功能


Posted in NodeJs onSeptember 03, 2019

node.js 复制文件夹

思路:

1、callback 驱动

2、递归所有需要复制文件

3、在一定阀值下并发复制文件

var async = require("async"); 
var fs = require("fs"); 
var path = require("path"); 
// cursively make dir  
function mkdirs(p, mode, f, made) { 
  if (typeof mode === 'function' || mode === undefined) { 
    f = mode; 
    mode = 0777 & (~process.umask()); 
  } 
  if (!made) 
    made = null; 
  var cb = f || function () {}; 
  if (typeof mode === 'string') 
    mode = parseInt(mode, 8); 
  p = path.resolve(p); 
  fs.mkdir(p, mode, function (er) { 
    if (!er) { 
      made = made || p; 
      return cb(null, made); 
    } 
    switch (er.code) { 
    case 'ENOENT': 
      mkdirs(path.dirname(p), mode, function (er, made) { 
        if (er) { 
          cb(er, made); 
        } else { 
          mkdirs(p, mode, cb, made); 
        } 
      }); 
      break; 
      // In the case of any other error, just see if there's a dir 
      // there already. If so, then hooray! If not, then something 
      // is borked. 
    default: 
      fs.stat(p, function (er2, stat) { 
        // if the stat fails, then that's super weird. 
        // let the original error be the failure reason. 
        if (er2 || !stat.isDirectory()) { 
          cb(er, made); 
        } else { 
          cb(null, made) 
        }; 
      }); 
      break; 
    } 
  }); 
} 
// single file copy 
function copyFile(file, toDir, cb) { 
  async.waterfall([ 
      function (callback) { 
        fs.exists(toDir, function (exists) { 
          if (exists) { 
            callback(null, false); 
          } else { 
            callback(null, true); 
          } 
        }); 
      }, function (need, callback) { 
        if (need) { 
          mkdirs(path.dirname(toDir), callback); 
        } else { 
          callback(null, true); 
        } 
      }, function (p, callback) { 
        var reads = fs.createReadStream(file); 
        var writes = fs.createWriteStream(path.join(path.dirname(toDir), path.basename(file))); 
        reads.pipe(writes); 
        //don't forget close the when all the data are read 
        reads.on("end", function () { 
          writes.end(); 
          callback(null); 
        }); 
        reads.on("error", function (err) { 
          console.log("error occur in reads"); 
          callback(true, err); 
        }); 
      } 
    ], cb); 
} 
// cursively count the files that need to be copied 
function _ccoutTask(from, to, cbw) { 
  async.waterfall([ 
      function (callback) { 
        fs.stat(from, callback); 
      }, 
      function (stats, callback) { 
        if (stats.isFile()) { 
          cbw.addFile(from, to); 
          callback(null, []); 
        } else if (stats.isDirectory()) { 
          fs.readdir(from, callback); 
        } 
      }, 
      function (files, callback) { 
        if (files.length) { 
          for (var i = 0; i < files.length; i++) { 
            _ccoutTask(path.join(from, files[i]), path.join(to, files[i]), cbw.increase()); 
          } 
        } 
        callback(null); 
      } 
    ], cbw); 
} 
// wrap the callback before counting 
function ccoutTask(from, to, cb) { 
  var files = []; 
  var count = 1; 
  function wrapper(err) { 
    count--; 
    if (err || count <= 0) { 
      cb(err, files) 
    } 
  } 
  wrapper.increase = function () { 
    count++; 
    return wrapper; 
  } 
  wrapper.addFile = function (file, dir) { 
    files.push({ 
      file : file, 
      dir : dir 
    }); 
  } 
  _ccoutTask(from, to, wrapper); 
} 
function copyDir(from, to, cb) { 
  if(!cb){ 
   cb=function(){}; 
  } 
  async.waterfall([ 
      function (callback) { 
        fs.exists(from, function (exists) { 
          if (exists) { 
            callback(null, true); 
          } else { 
            console.log(from + " not exists"); 
            callback(true); 
          } 
        }); 
      }, 
      function (exists, callback) { 
        fs.stat(from, callback); 
      }, 
      function (stats, callback) { 
        if (stats.isFile()) { 
          // one file copy 
          copyFile(from, to, function (err) { 
            if (err) { 
              // break the waterfall 
              callback(true); 
            } else { 
              callback(null, []); 
            } 
          }); 
        } else if (stats.isDirectory()) { 
          ccoutTask(from, to, callback); 
        } 
      }, 
      function (files, callback) {   
        // prevent reaching to max file open limit      
        async.mapLimit(files, 10, function (f, cb) { 
          copyFile(f.file, f.dir, cb); 
        }, callback); 
      } 
    ], cb); 
} 
var start = new Date().getTime(); 
copyDir("F:\\gear", "F:\\gear2", function (err) { 
  if (err) { 
    console.log("error ocur"); 
    console.dir(err); 
  } else { 
    console.log("copy ok"); 
    console.log("consume time:" + (new Date().getTime() - start)) 
  } 
});

总结

以上所述是小编给大家介绍的纯异步nodejs文件夹(目录)复制,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对三水点靠木网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

NodeJs 相关文章推荐
初始Nodejs
Nov 08 NodeJs
PHP和NodeJs开发的应用如何共用Session
Apr 16 NodeJs
你一定会收藏的Nodejs代码片段
Feb 04 NodeJs
简单好用的nodejs 爬虫框架分享
Mar 26 NodeJs
详解nodejs微信公众号开发——3.封装消息响应模块
Apr 10 NodeJs
使用vs code开发Nodejs程序的使用方法
Sep 21 NodeJs
NodeJs实现定时任务的示例代码
Dec 05 NodeJs
nodejs实现的连接MySQL数据库功能示例
Jan 25 NodeJs
nodejs图片处理工具gm用法小结
Dec 12 NodeJs
NodeJS读取分析Nginx错误日志的方法
May 14 NodeJs
Nodejs监控事件循环异常示例详解
Sep 22 NodeJs
nodejs中使用worker_threads来创建新的线程的方法
Jan 22 NodeJs
nodejs文件夹深层复制功能
Sep 03 #NodeJs
Nodejs中使用puppeteer控制浏览器中视频播放功能
Aug 26 #NodeJs
nodejs简单抓包工具使用详解
Aug 23 #NodeJs
nodejs使用node-xlsx生成excel的方法示例
Aug 22 #NodeJs
Nodejs libuv运行原理详解
Aug 21 #NodeJs
nodejs和react实现即时通讯简易聊天室功能
Aug 21 #NodeJs
Nodejs 识别图片类型的方法
Aug 15 #NodeJs
You might like
解析php file_exists无效的解决办法
2013/06/26 PHP
使用Discuz关键词服务器实现PHP中文分词
2014/03/11 PHP
php+mysqli实现将数据库中一张表信息打印到表格里的方法
2015/01/28 PHP
php获取网站百度快照日期的方法
2015/07/29 PHP
Yii框架防止sql注入,xss攻击与csrf攻击的方法
2016/10/18 PHP
YII框架http缓存操作示例
2019/04/29 PHP
JQuery打造PHP的AJAX表单提交实例
2009/11/03 Javascript
JavaScript实现同一页面内两个表单互相传值的方法
2015/08/12 Javascript
在node.js中怎么屏蔽掉favicon.ico的请求
2017/03/01 Javascript
Angularjs2不同组件间的通信实例代码
2017/05/06 Javascript
js用类封装pop弹窗组件
2017/10/08 Javascript
对 Vue-Router 进行单元测试的方法
2018/11/05 Javascript
使用Angular自定义字段校验指令的方法示例
2019/02/01 Javascript
vue项目中锚点定位替代方式
2019/11/13 Javascript
addEventListener()和removeEventListener()追加事件和删除追加事件
2020/12/04 Javascript
[02:06]2018完美世界全国高校联赛秋季赛开始报名(附彩蛋)
2018/09/03 DOTA
[01:08:30]DOTA2-DPC中国联赛 正赛 Ehome vs Elephant BO3 第一场 2月28日
2021/03/11 DOTA
用python实现面向对像的ASP程序实例
2014/11/10 Python
在Python下使用Txt2Html实现网页过滤代理的教程
2015/04/11 Python
python用10行代码实现对黄色图片的检测功能
2015/08/10 Python
Python使用urllib2模块抓取HTML页面资源的实例分享
2016/05/03 Python
基于python 字符编码的理解
2017/09/02 Python
python中urlparse模块介绍与使用示例
2017/11/19 Python
python 使用pandas计算累积求和的方法
2019/02/08 Python
Python ckeditor富文本编辑器代码实例解析
2020/06/22 Python
Pycharm2020.1安装中文语言插件的详细教程(不需要汉化)
2020/08/07 Python
python绘图pyecharts+pandas的使用详解
2020/12/13 Python
html5唤醒APP小记
2019/03/27 HTML / CSS
Doyoueven官网:澳大利亚健身服饰和配饰品牌
2019/03/24 全球购物
美丽乡村建设实施方案
2014/03/23 职场文书
2014社区三八妇女节活动方案
2014/03/30 职场文书
电子工程求职信
2014/07/17 职场文书
大学生实习推荐信
2015/03/27 职场文书
2016年基层党支部书记公开承诺书
2016/03/25 职场文书
2016年安康杯竞赛活动总结
2016/04/05 职场文书
PYTHON InceptionV3模型的复现详解
2022/05/06 Python