[英]When does the NodeJS request object emit events?
It seems I can attach multiple handlers to a request
and they will all receive events in the right order/time. 看来我可以将多个处理程序附加到一个
request
并且它们都将按正确的顺序/时间接收事件。 When exactly does a request
, which has already been received and emitted by the server - when does it emit the data/end events? 服务器何时已正确接收并发出了一个
request
,它何时发出数据/结束事件?
function handler1(req, res){
req.on('data', function(data){{
console.log("Handler 1 data");
});
req.on('end', function(){{
console.log("Handler 1 end");
});
}
function handler2(req, res){
req.on('data', function(data){{
console.log("Handler 2 data");
});
req.on('end', function(){{
console.log("Handler 2 end");
});
}
http.on('request', function(req, res){
handler1(req, res);
handler2(req, res);
});
// Handler1 data
// Handler2 data
// Handler1 end
// Handler2 end
The request object is an EventEmitter
object. 请求对象是一个
EventEmitter
对象。 As such, it emits events and anyone can add listeners for those events. 这样,它会发出事件,任何人都可以为这些事件添加侦听器。
In the case of the request object, it emits events that correspond with networking. 对于请求对象,它发出与联网相对应的事件。 The
data
event is emitted when some data has arrived (from the request body). 当某些数据到达时(从请求主体),将发出
data
事件。 If you have more than one listener for the data
event, then each listener will see each data
event with the exact same data. 如果您有一个以上的
data
事件侦听器,则每个侦听器将看到每个data
事件具有完全相同的数据。
The end
event is emitted where there is no more data to from the request body (all data has arrived). 在没有更多数据要从请求主体发送(所有数据已到达)的地方发出
end
事件。
Until you attach some means of reading the data from the incoming request (such as a data
event listener), the data is queued and will be held in memory. 除非您使用某种方法从传入的请求中读取数据(例如,
data
事件侦听器),否则数据将排队并保存在内存中。 This gives you a chance to attach the listener even after the data has already started arriving without any worry about missing any of the data. 即使在数据已经开始到达后,这也使您有机会连接侦听器,而不必担心丢失任何数据。 In node.js, many streams work this way.
在node.js中,许多流都以这种方式工作。 Data doesn't start flowing through the listeners until you attach at least one listener for the data.
直到您为数据附加至少一个侦听器,数据才开始流经侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.