我正在进行学习练习。在此函数中,我按列表列出目录和过滤文件。据我了解,如果我提供一个无效的目录名,它应该进入if
子句并退出。但相反,它转到if子句,然后抱怨else
子句中的某些内容。
模块:
module.exports = function (path, ext, callb) {
var fs = require('fs');
var elems = [];
var r = new RegExp("\\." + ext);
fs.readdir(path, function (err, list) {
console.log(err); // this runs, it's an object like { [Error: ENOENT, scandir '/Users/JohnnyLee/baobabf/
console.log(list); // this also runs, it's undefined
if (err) {
console.log("ERR!!!"); // this ran!
return callb(err);
} else {
console.log("NO ERRR!!!"); // this didn't run :/
list.forEach(function (i) { // this crashes?
if (i.match(r)) {
elems.push(i);
}
});
return callb(err, elems);
}
console.log(list);
});
};
可执行文件:
var mymod = require('./p06-1');
var filename = process.argv[2]
var extension = process.argv[3]
if (filename && extension) {
mymod(filename, extension, function (err, list) {
list.forEach(function (i) {
console.log(i);
});
})
}
输出:
triton:learnnode JohnnyLee$ node p06-2.js doesntexist txt
{ [Error: ENOENT, scandir 'doesntexist'] errno: -2, code: 'ENOENT', path: 'doesntexist' }
undefined
ERR!!!
/Users/JohnnyLee/learnnode/p06-2.js:7
list.forEach(function (i) {
^
TypeError: Cannot read property 'forEach' of undefined
at /Users/JohnnyLee/learnnode/p06-2.js:7:13
at /Users/JohnnyLee/learnnode/p06-1.js:11:20
at FSReqWrap.oncomplete (fs.js:95:15)
triton:learnnode JohnnyLee$
我错过了什么:(?
答案 0 :(得分:4)
你用:
来称呼它mymod(filename, extension, function (err, list) {
list.forEach(function (i) {
console.log(i);
});
})
那里的list.forEach
错误。查看错误的文件名/行号。这是因为您在模块中致电callb(err)
,但在假设list
与class Comment(models.Model):
article = models.ForeignKey(Article, null = True)
comic = models.ForeignKey(Comic, null = True)
assigned = models.BooleanField(initial=False)
合作之前,您不会检查错误。
答案 1 :(得分:0)
请正确检查错误堆栈,它响亮而清晰:)
关于你错过的问题,
添加错误检查语句以处理错误。
修改mymod
电话,如下所示,
if (filename && extension) {
mymod(filename, extension, function (err, list) {
if(err){
//do something with error
}else{
list.forEach(function (i) {
console.log(i);
}
});
})
}