2016-11-12 76 views
2

我試圖從一個Node.js的腳本傳遞函數回答另一個通參數功能從一個JS Node.js加載到另一個

這裏是我想。 Index.js

var express = require('express'); 

require('./meter'); 

var app = express(); 

app.get('/',function(req,res){ 
    return;     //hi function from another file 
}) 

app.listen(3000); 
console.log('listening on 3000 port') 

meter.js

module.exports = { 

    hi: function(req, res) { 
     return res.status(200).json({"message" : "Hello V1"}); 
    } 
}; 

確實需要的功能只是將做的工作?

在此先感謝。

+1

是的。但是你必須在'meter.js'中輸出'hi',你必須使用它,類似於你爲了表達而做的。 –

+0

謝謝@PratikGaikwad。但我明白你在說什麼,但不知道該怎麼做。請你可以在答案 –

+1

中寫一點代碼,請看下面Nir Levy發佈的答案。 –

回答

2

當您使用需要,你應該把它分配給一個變量,然後你就可以在你的代碼中使用它:

var express = require('express'); 
var meter = require('./meter'); // meter will be an object you can use later on 
var app = express(); 

app.get('/',meter.hi); // you actually don't need another annonimous function, can use hi directly as the callback 

app.listen(3000); 
console.log('listening on 3000 port') 
+0

謝謝@Nir Levy。完美工作。 :) –

2

由尼爾·利維的答案是正確的,但我會盡力給你關於發生了什麼的更多背景。

var express = require('express'); 
// Import the meter export and assign it a variable for reuse. 
var meter = require('./meter'); 
var app = express(); 
app.listen(3000); 
console.log('listening on 3000 port') 

按照尼爾的答案,你就用meter.hi處理GET請求/

app.get('/', meter.hi); 

究竟這裏發生的事情是JavaScript的通過了所有參數的meter.hi方法。在快遞的情況下,這裏將有3個參數 - requestresponsenext按此順序通過。

meter你只是使用請求和響應單獨模塊,這是很好的,但如果有需要的任何其他處理或meter.hi需要的參數來改變你可能要遵循以下做法。

app.get('/', function(req, res) { 
    // You can process the request here. 
    // Eg. authentication 
    meter.hi(req, res); 
}); 

如果你有過爭論更多的控制權傳遞給你的模塊。