function showFile() {
for(var i = 0; i< files.length; i++){
var itemFile = files[i];
fs.stat(__dirname + itemFile, function (err, stat){ //
if (stat.isDirectory()) {
console.log(' '+i+' \033[36m' +itemFile + '/\033[39m'); //
}else{
console.log(' '+i+' \033[90m' + itemFile + '\033[39m');
}
});
}
process.stdout.write('\033[33mEnter your choice: \033[39m');
}
上面的代码段在语法上是没有问题的,在执行的时候抛出了错误:
TypeError: Cannot read property 'isDirectory' of undefined
at ...\index.js:46:13
at FSReqWrap.oncomplete (fs.js:82:15)
这里错误在于使用synchronous的for循环.
如果使用下面的方法代替showFile(),it works!
function file(i) {
var filename = files[i];
/**
* fs.stat :
*/
fs.stat(__dirname + '/' + filename, function (err, stat){ //
if (stat.isDirectory()) {
console.log(' '+i+' \033[36m' +filename + '/\033[39m'); //
}else{
console.log(' '+i+' \033[90m' + filename + '\033[39m');
} i++; if (i== files.length) {
console.log('');
process.stdout.write('\033[33mEnter your choice: \033[39m');
process.stdin.resume();
}else{
file(i);
}
});
}