未记录的响应.已在node.js中完成 [英] Undocumented response.finished in node.js

查看:48
本文介绍了未记录的响应.已在node.js中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只需从node.js开始并遵循,然后在此处.TL; DR:完成(几乎)完成 response.end()后, finished 属性将设置为 true ( response http.OutgoingMessage 或子类的实例.

我实际上不得不不同意关于它不是比赛条件的评论,因为我认为是这样.即使 forEach 本身不是异步的,在这种情况下,它也会调用异步函数( writeHead() end()).如果这些功能花费一些时间,则对 response.finished 的检查可能会被调用得太早,并且最终将导致错误.

此外,我想知道是否应该完全使用 finished .它没有记录,也没有通过某种方法暴露于外界.换句话说,它可能现在就可以使用,但不能保证将来会继续使用.

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

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

解决方案

It's declared here and set here. TL;DR: when response.end() is (almost) done, the finished property is set to true (response is an instance of http.OutgoingMessage or a subclass).

I actually have to disagree with the comment about it not being a race condition, because I think it is. Even though forEach isn't asynchronous itself, in this case it calls asynchronous functions (writeHead() and end()). If those functions take a bit of time, the check for response.finished might be called too soon and you'll end up with an error.

Also, I wonder if finished should be used at all. It's not documented and not exposed to the outside world through a method. In other words, it might work now but there's no guarantee it will keep working in the future.

这篇关于未记录的响应.已在node.js中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆