刚开始使用node.js并关注Node Cookbook,但我仍然遇到了网址路由部分。
这是本书的代码:
var http = require('http');
var path = require('path');
var pages = [
{route: '', output: 'Woohoo!'},
{route: 'about', output: 'A simple routing with Node example'},
{route: 'another page', output: function() {return 'Here\'s '+this.route;}},
];
http.createServer(function (request, response) {
var lookup = path.basename(decodeURI(request.url));
pages.forEach(function(page) {
if (page.route === lookup) {
response.writeHead(200, {'Content-Type': 'text/html'});
response.end(typeof page.output === 'function'? page.output() : page.output);
}
});
if (!response.finished) { // couldn't find any documentation for response.finished
response.writeHead(404);
response.end('Page Not Found!');
}
}).listen(8080);
console.log('Server started');
虽然代码运行时没有任何错误,但似乎它符合他们的意思,但查看node.js documetation并在Google上搜索response.finished
并不会产生任何结果。
以下是本书在解释response.finished
请您解释一下该引文的实际含义或response.finished
的任何引用。
答案 0 :(得分:3)
截至此日期,记录了response.finish(实际上是根据v0.0.2中引入的文档)
来自the Node API Official Documentation,
response.finished
添加于:v0.0.2
布尔值,指示响应是否已完成。从假开始。在response.end()执行之后,该值将为true。
答案 1 :(得分:2)
宣布here并设置here。 TL; DR:当response.end()
(差不多)完成时,finished
属性设置为true
(response
是http.OutgoingMessage
的实例或子类)
我实际上不同意关于它不是竞争条件的评论,因为我认为它是。尽管forEach
本身不是异步的,但在这种情况下它会调用异步函数(writeHead()
和end()
)。如果这些功能需要一些时间,那么response.finished
的检查可能会很快被调用,您最终会收到错误消息。
另外,我想知道是否应该使用finished
。它没有记录,也没有通过方法暴露给外界。换句话说,它现在可能会起作用,但不能保证它将来会继续工作。