var fs = require('fs'),
stdin = process.stdin,
stdout = process.stdout;
var readFile = (dir) => {
let stats = [];
fs.readdir(dir, (err, files) => {
// called for each file walked in the directory
let file = (i) => {
let filename = files[i];
fs.stat(dir + '/' + filename, (err, stat) => {
stats[i] = stat;
if (stat.isDirectory()) {
console.log(' ' + i + ' \033[36m' + filename + '/\033[39m');
} else {
console.log(' ' + i + ' \033[90m' + filename + '\033[39m');
}
if (++i === files.length) {
read();
} else {
file(i);
}
});
};
// read user input when files are shown
let read = () => {
console.log('');
stdout.write(' \033[33mEnter your choice: \033[39m');
stdin.resume();
stdin.setEncoding('utf8');
stdin.on('data', option);
};
let option = (data) => {
let filename = files[Number(data)];
console.log(' ' + filename);
if (!filename) {
stdout.write(' \033[31mEnter your choice: \033[39m');
} else {
stdin.pause();
if (stats[Number(data)].isDirectory()) {
// 我想在这里回调 readFile 函数,从而对子目录下的文件执行同上的操作
// 请问该怎么写呢?
// readFile(dir + '/' + filename);
} else {
fs.readFile(dir + '/' + filename, 'utf8', (err, data) => {
console.log('');
console.log('\033[90m' + data.replace(/(.*)/g, ' $1') + '\033[39m');
});
}
}
};
file(0);
});
};
readFile(process.cwd());
如果直接回调 readFile 函数,会导致选中父目录与子目录中同编号的两个文件,最终使stat.isDirectory()执行失败
改这儿: