纯异步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全局安装和本地安装的不同之处
Jul 04 NodeJs
nodejs实例解析(输出hello world)
Jan 03 NodeJs
nodejs 实现钉钉ISV接入的加密解密方法
Jan 16 NodeJs
nodejs接入阿里大鱼短信验证码的方法
Jul 10 NodeJs
nodejs创建简易web服务器与文件读写的实例
Sep 07 NodeJs
使用vs code开发Nodejs程序的使用方法
Sep 21 NodeJs
Nodejs调用WebService的示例代码
Sep 29 NodeJs
nodejs连接mysql数据库及基本知识点详解
Mar 20 NodeJs
nodejs中使用archive压缩文件的实现代码
Nov 26 NodeJs
nodeJs的安装与npm全局环境变量的配置详解
Jan 06 NodeJs
使用nodejs实现JSON文件自动转Excel的工具(推荐)
Jun 24 NodeJs
Node.js实现爬取网站图片的示例代码
Apr 04 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中防止SQL注入攻击和XSS攻击的两个简单方法
2010/04/15 PHP
PHP5中GD库生成图形验证码(有汉字)
2013/07/28 PHP
php使用curl检测网页是否被百度收录的示例分享
2014/01/31 PHP
PHP字符串的递增和递减示例介绍
2014/02/11 PHP
php的memcache类分享(memcache队列)
2014/03/26 PHP
PHP根据传入参数合并多个JS和CSS文件的简单实现
2014/06/13 PHP
PHP获取windows登录用户名的方法
2014/06/24 PHP
PHP SPL标准库之数据结构堆(SplHeap)简单使用实例
2015/05/12 PHP
php 类自动载入的方法
2015/06/03 PHP
对PHP依赖注入的理解实例分析
2016/10/09 PHP
PHP下载远程图片的几种方法总结
2017/04/07 PHP
php上传后台无法收到数据解决方法
2019/10/28 PHP
基于jquery的无限级联下拉框js插件
2011/10/29 Javascript
js遍历td tr等html元素
2012/12/13 Javascript
jquery做的一个简单的屏幕锁定提示框
2014/03/26 Javascript
Css3制作变形与动画效果
2015/07/24 Javascript
详解页面滚动值scrollTop在FireFox与Chrome浏览器间的兼容问题
2015/12/03 Javascript
多个js毫秒倒计时同时进行效果
2016/01/05 Javascript
设计模式中的facade外观模式在JavaScript开发中的运用
2016/05/18 Javascript
基于js中style.width与offsetWidth的区别(详解)
2017/11/12 Javascript
js HTML DOM EventListener功能与用法实例分析
2020/04/27 Javascript
python调用java的Webservice示例
2014/03/10 Python
Python抓取淘宝下拉框关键词的方法
2015/07/08 Python
解决csv.writer写入文件有多余的空行问题
2018/07/06 Python
使用pandas实现csv/excel sheet互相转换的方法
2018/12/10 Python
jupyternotebook 撤销删除的操作方式
2020/04/17 Python
python 识别登录验证码图片功能的实现代码(完整代码)
2020/07/03 Python
matplotlib绘制正余弦曲线图的实现
2021/02/22 Python
解决pytorch 模型复制的一些问题
2021/03/03 Python
基于css3 animate制作绚丽的动画效果
2015/11/24 HTML / CSS
欧洲最大的高尔夫零售商:American Golf
2019/09/02 全球购物
私有程序集与共享程序集有什么区别
2013/04/05 面试题
学生感冒英文请假条
2014/02/04 职场文书
2015共产党员公开承诺书
2015/01/22 职场文书
求职简历自我评价范文
2015/03/10 职场文书
Springboot如何同时装配两个相同类型数据库
2021/11/17 Java/Android