2013-05-20 72 views
-1

我在做節點程序。我想從child訪問app.js參數。我在parent中使用了module.exports,在child中使用了module.parent.exports。但它沒有奏效。我該如何解決它?節點module.exports不起作用?

(/app.js)

var app = module.exports = express(); 

(/routes/index.js)

var app = module.exports = module.parent.exports; 
var port = app.get('port'); 

(出錯消息)

/Users/satoshi/Google Drive/node/testoy2/routes/index.js:7 
var port = app.get('port'); 
       ^
TypeError: Object #<Object> has no method 'get' 
    at Object.<anonymous> (/Users/satoshi/Google Drive/node/testoy2/routes/index.js:7:17) 
    at Module._compile (module.js:456:26) 
    at Object.Module._extensions..js (module.js:474:10) 
    at Module.load (module.js:356:32) 
    at Function.Module._load (module.js:312:12) 
    at Module.require (module.js:364:17) 
    at require (module.js:380:17) 
    at Object.<anonymous> (/Users/satoshi/Google Drive/node/testoy2/app.js:8:14) 
    at Module._compile (module.js:456:26) 
    at Object.Module._extensions..js (module.js:474:10) 

(版本)

node = v0.10.5 
express = 3.2.4 

回答

1

您應該使用

var app = require("../app.js"); 
index.js

+0

我試過了,但我得到了同樣的錯誤信息。 – satoshi

+0

你必須使用require來正確鏈接app.js中的express模塊​​。你做完了嗎? – zavg

+0

我在app.js中使用了require。如此,express = require('express') ,socketIO = require('socket.io') ,fs = require('fs') ,routes = require('./ routes') ,http = require ('http') ,path = require('path'); – satoshi

0

您可以通過app期間路由要求:
(app.js)

... 
var app = module.exports = express(); 
var routes = require('./routes')(app); 

然後確保將其存儲在路線:
(路由/ index.js)

var expApp = undefined;//This variable will hold the express app 
var routes = module.exports = function(app){ 
    expApp = app;//Now you have access to express 
} 

路由的其他任何出口都必須顯式導出。

+0

我試過了,但沒有奏效。我得到了同樣的錯誤。我也嘗試使用共享模塊。 /lib/share.js裏面的share.js是(module.exports = {};)(app.js)require('./ lib/share')。config = 3000; (index.js)要求( './../ LIB /股')。配置)。但它也沒有工作。我得到了「錯誤:無法找到模塊'../lib/share_valuable'」。 – satoshi

+0

@satoshi - 什麼都不起作用?我在我的應用程序中使用這種技術,並且工作正常。 –