纯异步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 相关文章推荐
基于promise.js实现nodejs的promises库
Jul 06 NodeJs
nodejs爬虫抓取数据之编码问题
Jul 03 NodeJs
浅析Nodejs npm常用命令
Jun 14 NodeJs
nodejs批量下载图片的实现方法
May 19 NodeJs
nodejs利用ajax实现网页无刷新上传图片实例代码
Jun 06 NodeJs
深入浅析Nodejs的Http模块
Jun 20 NodeJs
NodeJS 中Stream 的基本使用
Jul 30 NodeJs
nodejs实现一个word文档解析器思路详解
Aug 14 NodeJs
Nodejs Express 通过log4js写日志到Logstash(ELK)
Aug 30 NodeJs
Nodejs实现的操作MongoDB数据库功能完整示例
Feb 02 NodeJs
NodeJs使用webpack打包项目的方法详解
Feb 28 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设计模式 Adapter(适配器模式)
2011/06/26 PHP
通过php快速统计某个数据库中每张表的数据量
2012/09/04 PHP
thinkphp实现数组分页示例
2014/04/13 PHP
php实现基于pdo的事务处理方法示例
2017/07/21 PHP
jQuery入门第一课 jQuery选择符
2010/03/14 Javascript
Google 静态地图API实现代码
2010/11/19 Javascript
轻松创建nodejs服务器(9):实现非阻塞操作
2014/12/18 NodeJs
windows下安装nodejs及框架express
2015/08/07 NodeJs
详解javascript数组去重问题
2015/11/06 Javascript
javascript 中的 delete及delete运算符
2015/11/15 Javascript
基于jQuery实现音乐播放试听列表
2016/04/14 Javascript
Bootstrap3 内联单选和多选框
2016/12/29 Javascript
JS处理数据四舍五入(tofixed与round的区别详解)
2017/10/26 Javascript
微信小程序实现图片压缩功能
2018/01/26 Javascript
原生JavaScript实现remove()和recover()功能示例
2018/07/24 Javascript
微信小程序实现评论功能
2018/11/28 Javascript
Vue 组件修改根实例的数据的方法
2019/04/02 Javascript
微信小程序canvas开发水果老虎机的思路详解
2020/02/07 Javascript
Vue指令实现OutClick的示例
2020/11/16 Javascript
Python对小数进行除法运算的正确方法示例
2014/08/25 Python
python错误处理详解
2014/09/28 Python
Python中类型关系和继承关系实例详解
2015/05/25 Python
python3+opencv3识别图片中的物体并截取的方法
2018/12/05 Python
对Python 中矩阵或者数组相减的法则详解
2019/08/26 Python
Python单例模式的四种创建方式实例解析
2020/03/04 Python
使用Keras加载含有自定义层或函数的模型操作
2020/06/10 Python
CSS 3.0文字悬停跳动特效代码
2020/10/26 HTML / CSS
英国排名第一的礼品体验公司:Red Letter Days
2018/08/16 全球购物
印度首个本地在线平台:nearbuy
2019/03/28 全球购物
龟牌英国商店:Turtle Wax Brand Store UK
2019/07/02 全球购物
小学校园活动策划
2014/01/30 职场文书
购房协议书范本(无房产证)
2014/10/07 职场文书
人力资源部岗位职责
2015/02/11 职场文书
企业工会工作总结2015
2015/05/13 职场文书
2015年扶贫帮困工作总结
2015/05/20 职场文书
2016秋季幼儿园开学寄语
2015/12/03 职场文书