【发布时间】:2014-04-30 00:48:39
【问题描述】:
我是 node.js 的新手
我确实尝试过这个功能 (foo.js)
module.exports.hello = function hello(name) {
console.log("hello " + name);
}
hello('jack');
但我有这个错误
node foo.js
ReferenceError: hello is not defined
【问题讨论】:
我是 node.js 的新手
我确实尝试过这个功能 (foo.js)
module.exports.hello = function hello(name) {
console.log("hello " + name);
}
hello('jack');
但我有这个错误
node foo.js
ReferenceError: hello is not defined
【问题讨论】:
在module.exports 上创建一个函数不会使该函数全局可用,但它会使其在需要另一个文件中的文件时返回的对象上可用。
因此,如果我们从您的 foo.js 文件中删除对 hello 的调用:
module.exports.hello = function hello(name) {
console.log("hello " + name);
}
并在同一目录中创建另一个名为 bar.js 的文件:
var foo = require('./foo');
foo.hello('jack');
然后我们得到想要的输出:
tim [ ~/code/node-test ]$ node bar
hello jack
tim [ ~/code/node-test ]$
编辑:或者,如果您只想定义一个在该文件中使用的函数,您可以像这样在顶层定义一个常规函数:
function hello(name) {
console.log("hello " + name);
}
module.exports.hello = hello;
hello('jack');
请注意,通过将其添加到 module.exports,我们仍然可以使用 bar.js 中的函数,但如果您不需要此功能,则可以省略此行。
【讨论】:
module.exports.hello = hello; 和 exports.hello = hello 之间有什么区别?
exports 是module.exports 的别名。如果您只是在其上设置属性,我认为没有任何区别。见nodejs.org/docs/latest/api/modules.html#modules_module_exports
如果你真的想坚持上面定义的格式,你可以调用:
module.exports.hello = function hello(name) {
console.log("hello " + name);
}
module.exports.hello('jack');
或者更简洁的最后一行:
exports.hello('jack');
信用应该是here,因为这是我在第一次找到这个问题后想出答案的地方。
【讨论】:
我认为这是一个 JavaScript 错误,而不是 node.js 错误
module.exports.hello = function hello(name)
在我看来你正在尝试定义一个函数,但是 js 中的函数 def 有两种形式,一种是使用函数字面量,例如:
var x = function () {}
另一个是
function x () {}
而你似乎两者兼而有之
【讨论】: