我有下面的代碼段如下所示:捕獲返回的函數以JavaScript
function(staticPath) {
console.log('static Path = ' +staticPath);
return function(data, response) {
console.log('data = ' +data);
console.log('response = ' +response);
var readStream;
// Fix so routes to /home and /home.html both work.
data = data.replace(/^(\/home)(.html)?$/i, '$1.html');
data = '.' + staticPath + data;
fs.stat(data, function(error, stats) {
if (error || stats.isDirectory()) {
return exports.send404(response);
}
readStream = fs.createReadStream(data);
return readStream.pipe(response);
});
}
}
該函數基本上解析路徑到一個HTML文件,並顯示該文件的內容。
我無法理解如何從外部調用此方法。
我打電話它如下:
staticFile("D:\\Node Applications\\public\\home.html")
我可以捕獲它的可變innerFunc
內,我可以調用內部功能innerFunc(response)
其中響應是HTTP的serverResponse其中我有參考與我,但我不知道我怎麼能通過data
帕拉姆。
我不理解幕後發生了什麼。誰能解釋一下?我們經常在javascript中遇到這種類型的代碼嗎?
編輯: 爲了把事情說清楚: 還有另一種方法如下:
function(data, response) {
response.writeHead(200, {
'Content-Type': 'application/json'
});
response.end(JSON.stringify(data));
}
這是我從我的節點服務器的邏輯調用如下:
http.createServer(function(req, res) {
// A parsed url to work with in case there are parameters
var _url;
// In case the client uses lower case for methods.
req.method = req.method.toUpperCase();
console.log(req.method + ' ' + req.url);
if (req.method !== 'GET') {
res.writeHead(501, {
'Content-Type': 'text/plain'
});
return res.end(req.method + ' is not implemented by this server.');
}
if (_url is something like //localhost:1337/employees) {
//call employee service which returns *data*.
// send the data with a 200 status code
return responder.sendJson(data, res);
});
} else {
// try to send the static file
/*res.writeHead(200);
res.end('static file maybe');*/
console.log('Inside else');
var staticInner = responder.staticFile("D:\\Node Applications\\public\\home.html");
staticInner(res);
}
// res.end('The current time is ' + Date.now())
}).listen(1337, '127.0.0.1');
正如人們所看到有沒有數據變量傳遞給innerFunc因此,感到困惑。
你明白這個功能應該做什麼嗎?如果你不知道如何傳遞數據(我認爲你的意思是你不知道'data'是什麼,因爲你可以將它作爲'innerFunc(data,response)')來傳遞,我會說你不會不知道這個功能是幹什麼的。很高興知道這一點。此外,你是否期望得到這樣的結果:'返回readStream.pipe(響應)',或者什麼? – Parziphal
你說得對。我編輯了我的問題,因爲您可以看到我沒有'data'變量將它傳遞給函數。最初,我以爲我可能會錯過一些理解,但似乎數據變量是我需要將它傳遞給函數。 你能解釋什麼可能是這裏從函數返回函數的原因?對於所有這些都需要什麼? 謝謝! – Adithya