2013-02-25 20 views
1

簡單地說:我怎樣才能製作require()require(),然後用exportsexports將數據恢復爲原來的?Node.js:遞歸需求和出口

這是一個實際的例子:

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) 

任何幫助嗎?這種情況並不那麼棘手:我想用一個唯一的入口腳本將我的腳本分組到一個文件夾中,該腳本將在各種其他文件中調用函數。

在此先感謝。

+0

我猜你必須命名出口 – pfried 2013-02-25 13:15:13

回答

4

您不要在出口上設置任何值。你必須這樣做,否則exports.text = text出口沒有價值

hello.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); 
+0

偉大的朋友!有用。非常感謝你的幫助。 – htaidirt 2013-02-25 13:25:30