0

Just starting off with node.js and following Node Cookbook but I am stuck on URL routing part.

here is the code from the book itself:

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');

Though code runs without any errors and seems it does what they meant but looking to the node.js documetation and searching on Google for response.finished doesn't yields any result.

and here is the quote from the book in context of explaining response.finished

response.finished

Could you please explain what the actually meant by that quotation or any citation for response.finished.

4

2 回答 2

3

截至目前,response.finish 已记录在案(实际上是根据 v0.0.2 中引入的文档)

Node API 官方文档

响应完成

添加于:v0.0.2

指示响应是否已完成的布尔值。开始为假。response.end() 执行后,该值将为真。

于 2017-04-12T19:51:13.850 回答
2

它在此处声明并此处设置。TL;DR:当(几乎)完成时,属性设置为(是一个实例或一个子类)。response.end()finishedtrueresponsehttp.OutgoingMessage

我实际上不得不不同意关于它不是比赛条件的评论,因为我认为它是。尽管forEach它本身不是异步的,但在这种情况下它调用异步函数(writeHead()end())。如果这些函数需要一些时间,则检查response.finished可能会被调用得太快,最终会出现错误。

另外,我想知道是否finished应该使用。它没有记录在案,也没有通过某种方法暴露给外界。换句话说,它现在可能有效,但不能保证将来会继续有效。

于 2013-04-29T15:37:13.007 回答