当我运行此代码时,我不断返回undefined
:
var fs = require('fs'),
path = require('path'),
filepath = process.argv[2];
function listFilesByExtension(path_to_file, ext) {
fs.readdir(path_to_file, function (err, files) {
if (err) {
console.log(err);
} else {
console.log(files);
}
});
}
console.log(listFilesByExtension(filepath, 'txt'));
console.log(files)
返回:
undefined
[ 'CHANGELOG.md',
'LICENCE.md',
'README.md',
'api.html',
'dat',
'data.dat',
'data.json',
'learnyounode.dat',
'learnyounode.sql',
'learnyounode.txt',
'md',
'w00t.dat',
'w00t.txt',
'words.dat',
'wrrrrongdat' ]
所以 undefined
不是来自那里,console.log(err)
也返回 null
。
有人可以向我解释一下为什么会发生这种情况吗?谢谢
最佳答案
这是因为你的listFilesByExtension
函数不返回任何内容,所以你的 console.log
对于此函数调用将输出 undefined
.
这一行是原因:
console.log(listFilesByExtension(filepath, 'txt'));
如果删除 console.log
形成这条线,你意想不到undefined
将会消失。
listFilesByExtension(filepath, 'txt');
关于Javascript 未知未定义返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33515770/