【发布时间】:2013-07-16 23:01:58
【问题描述】:
在使用 Node.js 创建基本 HTTP 服务器时,我注意到“http.ServerResponse”对象的 res.write 和 res.end 方法都可以接受如下回调函数:
require('http').createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello ', function() { console.log('here 1'); });
res.end(' World', function() { console.log('here 2'); });
}).listen(1337, '127.0.0.1');
'Hello World'在浏览器中输出,'here 1'和'here 2'在终端中输出。
但是,这些回调参数在任何地方都没有记录,例如 http://nodejs.org/api/http.html#http_response_end_data_encoding,除非我遗漏了什么。
我真的可以使用这些回调函数吗?我有一个有趣的用例。还是它们是一些内部使用的东西,应该避免?
【问题讨论】:
-
它很可能
res.write('hi', function(err) {});也可能是另外一个参数,但我从未使用它传递单数(err) -
response.write 不提供错误回调。第二个参数应该只是编码。
-
我挖掘了节点代码,并没有真正找到这些函数是如何执行的。下面是这些函数的两个定义。 github.com/joyent/node/blob/master/lib/_http_outgoing.js#L393 github.com/joyent/node/blob/master/lib/_http_outgoing.js#L468 你可以跟随编码值,你最终会在github.com/joyent/node/blob/master/lib/_http_outgoing.js#L147
-
然后,如果您查看 net 模块中的 connection.write,您将看到编码和 cb 可以是可选的。那就是它实际被调用的地方。
-
啊,我想我需要再往兔子洞深处走一步。