遍历文件

使用 fs 模块遍历文件,有递归、非递归两种方式

递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function travel(dir, callback) {
fs.readdirSync(dir).forEach(function (file) {
var pathname = path.join(dir, file);

if (fs.statSync(pathname).isDirectory()) {
travel(pathname, callback);
} else {
callback(pathname);
}
});
}

// 调用
travel('c:\\workspace\\nodejs\\public', (pathname) => {
console.log(pathname);
});

非递归:

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
29
function travel(dir, callback, finish) {
fs.readdir(dir, function (err, files) {
(function next(i) {
if (i < files.length) {
var pathname = path.join(dir, files[i]);

fs.stat(pathname, function (err, stats) {
if (stats.isDirectory()) {
travel(pathname, callback, function () {
next(i + 1);
});
} else {
callback(pathname, function () {
next(i + 1);
});
}
});
} else {
finish && finish();
}
}(0));
});
}

// 调用
travel('c:\\workspace\\nodejs\\public', (pathname, next) => {
console.log(pathname);
next();
});