0%

NodeJS 递归读取文件夹内容

整理一下遍历文件夹所有文件内容的几个方法

Glob

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const glob = require('glob');
const path = require('path');
const fs = require('fs-extra');

function getDirectories(src, callback) {
glob(src + '/**/*', callback);
}

getDirectories(srcPath, async function (err, res) {
if (err) {
console.log('Error', err);
} else {
for (let index = 0; index < res.length; index++) {
const element = res[index];
// 这段代码是检查是否文件夹的
if (!fs.lstatSync(element).isDirectory()) {
await readFile(element);
}
}
}
});

async function readFile(params) {
return fs.readFile(params, 'utf8').then((e) => {
console.log('这是读取的文件内容', e);
return e;
});
}

原生fs

简单实现

1
2
3
4
5
6
7
8
9
10
11
function traverseDir(dir) {
fs.readdirSync(dir).forEach(file => {
let fullPath = path.join(dir, file);
if (fs.lstatSync(fullPath).isDirectory()) {
console.log(fullPath);
traverseDir(fullPath);
} else {
console.log(fullPath);
}
});
}

并行遍历文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var fs = require('fs');
var path = require('path');
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach(function(file) {
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
results.push(file);
if (!--pending) done(null, results);
}
});
});
});
};

串行遍历文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var fs = require('fs');
var path = require('path');
var walk = function(dir, done) {
var results = [];
fs.readdir(dir, function(err, list) {
if (err) return done(err);
var i = 0;
(function next() {
var file = list[i++];
if (!file) return done(null, results);
file = path.resolve(dir, file);
fs.stat(file, function(err, stat) {
if (stat && stat.isDirectory()) {
walk(file, function(err, res) {
results = results.concat(res);
next();
});
} else {
results.push(file);
next();
}
});
})();
});
};

使用

1
2
3
4
walk(process.env.HOME, function(err, results) {
if (err) throw err;
console.log(results);
});

后记

这儿有很多优秀的方法