与旧 Node.js 版本的兼容性
【Compatibility with older Node.js versions】
在 Node.js 0.10 之前,Readable 流接口更简单,但功能也更弱,实用性也较低。
【Prior to Node.js 0.10, the Readable stream interface was simpler, but also
less powerful and less useful.】
- 与其等待对
stream.read()方法的调用,'data'事件将立即开始发出。需要进行一定工作以决定如何处理数据的应用必须将读取的数据存储到缓冲区,以免数据丢失。 stream.pause()方法是建议性的,而不是保证性的。这意味着即使在流处于暂停状态时,也仍然需要准备好接收'data'事件。
在 Node.js 0.10 中,添加了 Readable 类。为了与旧的 Node.js 程序向后兼容,当添加 'data' 事件处理程序或调用 stream.resume() 方法时,Readable 流会切换到“流动模式”。其效果是,即使不使用新的 stream.read() 方法和 'readable' 事件,也无需再担心丢失 'data' 块。
【In Node.js 0.10, the Readable class was added. For backward
compatibility with older Node.js programs, Readable streams switch into
"flowing mode" when a 'data' event handler is added, or when the
stream.resume() method is called. The effect is that, even
when not using the new stream.read() method and
'readable' event, it is no longer necessary to worry about losing
'data' chunks.】
虽然大多数应用将继续正常运行,但在以下条件下,这会引入一个极端情况:
【While most applications will continue to function normally, this introduces an edge case in the following conditions:】
- 未添加
'data'事件监听器。 stream.resume()方法从未被调用。- 该流未被导向任何可写目标。
例如,考虑以下代码:
【For example, consider the following code:】
// WARNING! BROKEN!
net.createServer((socket) => {
// We add an 'end' listener, but never consume the data.
socket.on('end', () => {
// It will never get here.
socket.end('The message was received but was not processed.\n');
});
}).listen(1337); 在 Node.js 0.10 之前,传入的消息数据会被简单地丢弃。然而,在 Node.js 0.10 及更高版本中,套接字会永远保持暂停状态。
【Prior to Node.js 0.10, the incoming message data would be simply discarded. However, in Node.js 0.10 and beyond, the socket remains paused forever.】
在这种情况下的解决方法是调用 stream.resume() 方法来开始数据的流动:
【The workaround in this situation is to call the
stream.resume() method to begin the flow of data:】
// Workaround.
net.createServer((socket) => {
socket.on('end', () => {
socket.end('The message was received but was not processed.\n');
});
// Start the flow of data, discarding it.
socket.resume();
}).listen(1337); 除了新的 Readable 流切换到流动模式外,0.10 之前风格的流也可以使用 readable.wrap() 方法封装到 Readable 类中。
【In addition to new Readable streams switching into flowing mode,
pre-0.10 style streams can be wrapped in a Readable class using the
readable.wrap() method.】