纯异步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 相关文章推荐
抛弃Nginx使用nodejs做反向代理服务器
Jul 17 NodeJs
Nodejs极简入门教程(一):模块机制
Oct 25 NodeJs
Nodejs学习笔记之Stream模块
Jan 13 NodeJs
NodeJS学习笔记之Http模块
Jan 13 NodeJs
nodejs事件的监听与触发的理解分析
Feb 12 NodeJs
NodeJS配置HTTPS服务实例分享
Feb 19 NodeJs
初识NodeJS服务端开发入门(Express+MySQL)
Apr 07 NodeJs
nodejs操作mongodb的增删改查功能实例
Nov 09 NodeJs
nodejs使用redis作为缓存介质实现的封装缓存类示例
Feb 07 NodeJs
Nodejs Express 通过log4js写日志到Logstash(ELK)
Aug 30 NodeJs
nodejs读取本地中文json文件出现乱码解决方法
Oct 10 NodeJs
nodejs如何在package.json中设置多条启动命令
Mar 16 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使HTML标签自动补全闭合函数代码
2012/10/04 PHP
php+ajax实现无刷新数据分页的办法
2015/11/02 PHP
CodeIgniter记录错误日志的方法全面总结
2016/05/17 PHP
php设计模式之单例模式代码
2016/06/11 PHP
php使用lua+redis实现限流,计数器模式,令牌桶模式
2019/04/04 PHP
PHP7匿名类的用法示例
2019/04/05 PHP
基于thinkphp6.0的success、error实现方法
2019/11/05 PHP
JavaScript 参考教程
2006/12/29 Javascript
js href的用法
2010/05/13 Javascript
Javascript实现仿WebQQ界面的“浮云”兼容 IE7以上版本及FF
2011/04/27 Javascript
jquery select 设置默认选中的示例代码
2014/02/07 Javascript
JavaScript中的console.log()函数详细介绍
2014/12/29 Javascript
jquery用ajax方式从后台获取json数据后如何将内容填充到下拉列表
2015/08/26 Javascript
如何在Angular2中使用jQuery及其插件的方法
2017/02/09 Javascript
canvas压缩图片转换成base64格式输出文件流
2017/03/09 Javascript
node.js学习之断言assert的使用示例
2017/09/28 Javascript
利用Node.js批量抓取高清妹子图片实例教程
2018/08/02 Javascript
详解jQuery如何实现模糊搜索
2019/05/10 jQuery
深入了解Hybrid App技术的相关知识
2019/07/17 Javascript
Vue中this.$nextTick的作用及用法
2020/02/04 Javascript
vue中移动端调取本地的复制的文本方式
2020/07/18 Javascript
[02:01]2018完美盛典-开场舞《双子星》
2018/12/16 DOTA
解密Python中的描述符(descriptor)
2015/06/03 Python
python中WSGI是什么,Python应用WSGI详解
2017/11/24 Python
pandas ix &amp;iloc &amp;loc的区别
2019/01/10 Python
解决python给列表里添加字典时被最后一个覆盖的问题
2019/01/21 Python
Python: tkinter窗口屏幕居中,设置窗口最大,最小尺寸实例
2020/03/04 Python
python3 使用openpyxl将mysql数据写入xlsx的操作
2020/05/15 Python
Django静态文件加载失败解决方案
2020/08/26 Python
Python实现自动装机功能案例分析
2020/10/22 Python
ASP.NET Core中的配置详解
2021/02/05 Python
Sperry澳大利亚官网:源自美国帆船鞋创始品牌
2019/07/29 全球购物
台湾良兴购物网:EcLife
2019/12/01 全球购物
《那片绿绿的爬山虎》教学反思
2014/02/27 职场文书
教师职业道德事迹材料
2014/08/18 职场文书
关于MySQL临时表为什么可以重名的问题
2022/03/22 MySQL