2017-10-28 51 views
0

試圖從require傳遞responseHandler而不是將它放在同一個文件中,但獲取錯誤偵聽器參數必須是函數。 console.log需要返回,返回一個函數,所以我沒有看到這個問題?nodejs http偵聽器參數必須是函數

var responseHandler = require("./downloader.js"); 
log(responseHandler); // Logs [Functions: responseHandler) 
request = https.get(fileUrl, responseHandler); // Error "listener" argument must be a function (according to the log line above, it is!?) 

如果我換出1號線爲downloader.js一切工作正常的內容... downloader.js的

內容只是

var responseHandler = function(response){ 
    // some code to process response.statusCode 
    response.on('data',function(chunk){//stuff}); 
    response.on('error',function(e){//stuff}); 
    response.on('end',function(e){//stuff}); 
} 
exports.responseHandler = responseHandler; 

我想保持主要文件乾淨而小,並有此工作作爲一個要求,想法?

回答

1

如果你只想要導出功能你可以做到這一點:

module.exports = responseHandler; 

然後導入值將在功能,而不是一個函數值的對象:

var responseHandler = require("./downloader.js"); 
+0

Doh ...我用錯誤的方式輸出... tks – Darcey

1

你需要嘗試做:

request = https.get(fileUrl, responseHandler.responseHandler); 

要導出的是有一個名爲ResponseHandler所函數的對象,所以你需要把它直接

+0

這似乎更正確,因爲如果'.js'文件中存在多個函數,那麼您不能只導出單個函數。 – wrangler

相關問題