【问题标题】:Node.js: recursive require and exportsNode.js:递归需求和导出
【发布时间】:2013-02-25 13:05:00
【问题描述】:

简单地说:我怎样才能使require () 的require(),然后用exports 的exports 恢复数据?

这是一个实际的例子:

我的hello.js 文件:

var text = "Hello world!"
exports.text

在同一个文件夹中,我有foo.js 文件:

var hello = require("./hello.js")
exports.hello

最后,我的app.js 文件(也在同一个文件夹中):

var foo = require("./foo.js")
console.log(foo.hello.text)

我期待它返回:

Hello world!

但是相反,它返回一个错误:

/Users/Hassinus/www/node/test/app.js:2
console.log(foo.hello.text)
                     ^
TypeError: Cannot read property 'text' of undefined
at Object.<anonymous> (/Users/Hassen/www/node/test/app.js:2:22)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

有什么帮助吗?这种情况并没有那么棘手:我想将我的脚本分组到一个文件夹中,其中包含一个唯一的入口脚本,它将调用其他各种文件中的函数。

提前致谢。

【问题讨论】:

  • 我猜你必须命名出口

标签: node.js module


【解决方案1】:

您没有对导出设置任何值。您必须执行exports.text = text 之类的操作,否则导出没有价值

你好.js

var text = "Hello world!";
exports.text = text;

foo.js 文件:

var hello = require("./hello.js");
exports.hello = hello;

app.js 文件

var foo = require("./foo.js");
console.log(foo.hello.text);

【讨论】:

    猜你喜欢
    • 2016-11-09
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    相关资源
    最近更新 更多