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