展开目录
nodejs遍历文件夹
nodejs
X
陈尼玛的博客
记录开发生涯的踩坑经历,用时间来验证成长
加载中

复习nodejs,写了一个遍历文件夹内文件的工具。效率比系统自带的搜索文件功能慢一点点,好处是调用方便,通过事件来通知发现的文件或者目录。

dir.js模块代码

/******

 last update: 2016-11-16
 author: treemonster
 https://treemonster.github.io/
********/

var fs=require('fs');
var path=require('path');

module.exports=function(dir){
  var ev=new (require('events'));
  var dirs=[];
  void function loop(dir){
    fs.readdir(dir,function(e,files){
      if(e)return ev.emit('error',dir);
      else ev.emit('dir',path.resolve(dir));
      Promise.all(files.map(function(file){
          var defer=Promise.defer();
        var full=dir+path.sep+file;
        fs.stat(full,function(e,stats){
          defer\[e?'reject':'resolve'](stats);
        });
        return defer.promise.then(function(stats){
          if(stats.isDirectory())dirs.push(full);
          else ev.emit('file',path.resolve(full));
        },function(e){
          ev.emit('error',full);
        });
      })).then(function(){
        dirs.length?loop(dirs.shift()):ev.emit('finish');
      });
    });
  }(dir);
  ev.on('error',()=>{})
  return ev;
};

用法

var f=require('./dir');
new f('/').on('file',function(file){
  console.log('file found:',file)
}).on('dir',function(dir){
  console.log('dir found:',dir);
}).on('finish',function(){
  console.log('search completed');
})

相关文档

  1. 记一次nodejs内存泄漏的排查经历

  2. nodejs 长连接

  3. npm包命令行调用

  4. nodejs本地双向代理 端口转发

  5. nodejs socks5

  6. nodejs俄罗斯方块

  7. webrtc服务搭建

  8. ssl 证书生成方式

  9. nodejs建立多级目录

  10. linux 上配置node路径

  11. nodejs处理gb2312编码

  12. 读取Blob的内容实体

  13. nodejs那恶心的stream.Readable

  14. Promise复习,nodejs异步建立多级目录

  15. 异步并发也要保证原子性

  16. 简易命令行解析器

  17. Promise才是javascript的正统队列

  18. callback => Promise.then

  19. 简易转义字符转实体字符方法

随便看看

  1. word文件命令行打印

  2. ipsec vpn 添加新账号

  3. css3 文字渐变色

  4. SSL certificate problem: self signed certificate in certificate chain

  5. nodejs socks5

  6. jxa运动指令脚本

  7. 树莓派实现用pi用户自动登录

  8. nodejs俄罗斯方块

  9. heroku查看app使用时间

  10. mongodb 批量修改字段语句

  11. webrtc泄漏本地ip信息

  12. 把树莓派的存储空间拓展到整张TF卡中

  13. python下载文件,带进度条控制

  14. mac搜索局域网内的主机

  15. 树莓派配置wifi

  16. replace2正则扩展方法

  17. centos7 开放或者关闭端口

畅言模块加载中