【问题标题】:node export module unknown console log "undefined"节点导出模块未知控制台日志“未定义”
【发布时间】:2019-02-17 13:34:11
【问题描述】:

所以我正在学习使用 node.js 导出模块

在 test.js 中我有(test.js 是编写模块的地方)

var Library={
    name:"Timmy",
    greet:function(name){
        console.log("Hello from the "+ name);
    }
}
module.exports.Library=Library;

在 server.js 我有:

var test=require('./test.js'); 
console.log(test.Library.greet())

然后当我在终端中运行 node server.js 时,它会给出:

Hello from the Timmy library.
undefined

这个“未定义”是什么意思?出错了?

我在这里发现了类似的问题,但是这个例子太复杂了,我无法理解.. Node Module Export Returning Undefined

【问题讨论】:

  • hmm...所以 test.js,需要自己吗?我以前从未见过(也许有充分的理由?)
  • test.js 是否位于包含 server.js 的完全相同的文件夹中?
  • 是的,位置相同
  • 对不起我是愚蠢的..

标签: node.js module


【解决方案1】:

所以这就是发生的事情: server.js 文件中的控制台打印函数调用的返回。 现在,由于您的函数调用 (test.Library.greet()) 没有显式返回任何内容,因此它隐式返回 undefined

这就是要打印的内容。

【讨论】:

  • 抱歉打错了..还是有问题
【解决方案2】:

我做了一些实验, 终于知道为什么undefined会出现了:

server.js请把这段代码分开

console.log(test.Library.greet())

var str = test.Library.greet();
console.log(str);

你就会知道 当你做console.log("Hello from the "+ name) => 你会得到第一行输出

Hello from the xxxx

但是因为你写的greet()没有返回值
test.Library.greet() => 将得到 undefined

所以第二行:console.log(test.Library.greet()) 将是

undefined

有趣的问题:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    • 2021-08-15
    • 2018-07-16
    • 1970-01-01
    • 2015-03-31
    • 2014-09-21
    • 2016-06-04
    相关资源
    最近更新 更多