Javascript 未知未定义返回

标签 javascript node.js

当我运行此代码时,我不断返回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/

相关文章:

javascript - 单击 AngularJS 按钮时如何滚动

javascript - 测试是否使用 "every"获取项目未按预期工作

Node.js 和 Redis

javascript - 在 V8 JavaScript (Chrome & Node.js) 中访问行号

javascript - Cron Job 每天运行多次

javascript - 获取并使用背景颜色在其他窗口中应用相同的颜色

javascript - 如何在移动设备中加载特定的 jquery 代码

javascript - "Mongoose mpromise is deprecated"

node.js - 在 NodeJS 中将 Jimp 模块与 Amazon AWS S3 结合起来

node.js - AWS Lambda 函数可以调用另一个函数吗