2016-10-05 35 views
0

文件對於一個項目,我使用的網模塊來創建一個「迷你Web框架」JavaScript的回調 - 處理讀取與fs.readFile

我遇到了很多麻煩處理這一回調

var sendFile(path) { 
    fs.readFile(path, config, this.handleRead.bind(this)); 
} 

其中READFILE被定義爲:

var handleRead = function(contentType, data, err) { 
    if (err) { 
    console.log(err);   //returns properly 
    } else { 
    console.log(data);  //returns properly 
    console.log(contentType) //returning undefined 
} 

到目前爲止,此代碼的工作在我能趕上的錯誤和正確寫入數據的意義。

我的問題是:如何通過回調來發送contentType?

我試過 -

var sendFile(path) { 
    var contentType = ContentType['the path type'] 
    fs.readFile(path, config, this.handleRead(contentType).bind(this)); 
} 

但隨後這將導致數據和犯錯是未定義的。

我對js很陌生,對於如何使用回調工作仍然感到困惑。任何輸入是讚賞!

+0

那麼,什麼'readFile'?你已經向我們展示了'handleRead',但不是它的調用方式。 –

+0

嗨@RocketHazmat readFile是我導入的模塊fs中的方法。 handleRead在readFile中作爲第三個參數被調用:'fs.readFile(path,config,this.handleRead.bind(this));' –

+0

這只是將回調傳遞給'readFile'方法。它不顯示如何/何時被調用。 'this.handleRead.bind(this)'只是一個需要在某個時刻運行/調用的函數。 –

回答

1

.bind()讓您不僅僅設置「上下文」(this函數的值)。你也可以在函數中「綁定」參數。

嘗試:

function sendFile(path) { 
    var contentType = ContentType['the path type'] 
    fs.readFile(path, config, this.handleRead.bind(this, contentType)); 
} 

這將通過與它的上下文的回調設置爲任何this是和它的第一個參數設置爲contentType。只要這個回調被稱爲data(也可能是err),那麼一切都會起作用。