node 遍历目录下所有文件

安装方法

 npm install rd --save
var rd = require('rd');

// 异步列出目录下的所有文件
rd.read('/tmp', function (err, files) {
  if (err) throw err;
  // files是一个数组,里面是目录/tmp目录下的所有文件(包括子目录)
});

// 同步列出目录下的所有文件
var files = rd.readSync('/tmp');

// 异步遍历目录下的所有文件
rd.each('/tmp', function (f, s, next) {
  // 每找到一个文件都会调用一次此函数
  // 参数s是通过 fs.stat() 获取到的文件属性值
  console.log('file: %s', f);
  // 必须调用next()才能继续
  next();
}, function (err) {
  if (err) throw err;
  // 完成
});

// 同步遍历目录下的所有文件
rd.eachSync('/tmp', function (f, s) {
  // 每找到一个文件都会调用一次此函数
  // 参数s是通过 fs.stat() 获取到的文件属性值
  console.log('file: %s', f);
});

源码:https://github.com/leizongmin/node-rd

猜你喜欢

转载自482739566.iteye.com/blog/2361905