纯异步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进程管理模块forever详解
Jun 01 NodeJs
nodejs创建web服务器之hello world程序
Aug 20 NodeJs
Nodejs Express4.x开发框架随手笔记
Nov 23 NodeJs
nodeJs链接Mysql做增删改查的简单操作
Feb 04 NodeJs
3分钟快速搭建nodejs本地服务器方法运行测试html/js
Apr 01 NodeJs
Nodejs 和Session 原理及实战技巧小结
Aug 25 NodeJs
nodejs结合socket.io实现websocket通信功能的方法
Jan 12 NodeJs
NodeJS加密解密及node-rsa加密解密用法详解
Oct 12 NodeJs
NodeJs操作MongoDB教程之分页功能以及常见问题
Apr 09 NodeJs
nodejs二进制与Buffer的介绍与使用
Jul 11 NodeJs
使用nodeJS中的fs模块对文件及目录进行读写,删除,追加,等操作详解
Feb 06 NodeJs
linux 下以二进制的方式安装 nodejs
Feb 12 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下对字符串的递增运算代码
2010/08/21 PHP
PHP 获取ip地址代码汇总
2015/07/05 PHP
浅谈关于PHP解决图片无损压缩的问题
2017/09/01 PHP
php传值和传引用的区别点总结
2019/11/19 PHP
获取当前网页document.url location.href区别总结
2008/05/10 Javascript
Js动态创建div
2008/09/25 Javascript
js 鼠标拖动对象 可让任何div实现拖动效果
2009/11/09 Javascript
js动态添加onload、onresize、onscroll事件(另类方法)
2012/12/26 Javascript
深入剖析javascript中的exec与match方法
2016/05/18 Javascript
JS HTML5拖拽上传图片预览
2016/07/18 Javascript
jquery组件WebUploader文件上传用法详解
2020/10/23 Javascript
vue元素实现动画过渡效果
2017/07/01 Javascript
vue的diff算法知识点总结
2018/03/29 Javascript
浅谈Node 异步IO和事件循环
2019/05/05 Javascript
Python中如何优雅的合并两个字典(dict)方法示例
2017/08/09 Python
python 动态加载的实现方法
2017/12/22 Python
face++与python实现人脸识别签到(考勤)功能
2019/08/28 Python
wxPython多个窗口的基本结构
2019/11/19 Python
pyhton中__pycache__文件夹的产生与作用详解
2019/11/24 Python
Python能做什么
2020/06/02 Python
Python字符串三种格式化输出
2020/09/17 Python
CSS3使用border-radius属性制作圆角
2014/12/22 HTML / CSS
澳大利亚排名第一的狂热牛仔品牌:ONETEASPOON
2018/11/20 全球购物
英国打印机墨盒销售网站:Ink Factory
2019/10/07 全球购物
国际贸易专业个人求职信范文分享
2013/12/14 职场文书
库房主管岗位职责
2013/12/31 职场文书
开会迟到检讨书
2014/01/08 职场文书
校友会欢迎辞
2014/01/13 职场文书
医务工作者先进事迹材料
2014/01/26 职场文书
《望洞庭》教学反思
2014/02/16 职场文书
《小蝌蚪找妈妈》教学反思
2014/02/21 职场文书
2015年政府采购工作总结
2015/05/21 职场文书
美丽的大脚观后感
2015/06/03 职场文书
结婚典礼主持词
2015/06/29 职场文书
民主生活会主持词
2015/07/01 职场文书
幼儿园卫生保健制度
2015/08/05 职场文书