在玩流和缓冲区时,我遇到了一个问题:
我编写了以下愚蠢的程序:
const net = require('net');
const stream = require('stream');
class MyReadable extends stream.Readable {
constructor(options) {
super(options);
}
_read(size) {
let value = Math.floor(Math.random() * 10);
this.push(value > 8 ? null : value.toString())
}
}
const server = net.createServer((client) => {
const readStream = new MyReadable()
readStream.pipe(client)
client.pipe(process.stdout)
readStream.on('end', () => {
console.log('done')
client.destroy()
readStream.destroy()
})
})
server.listen(7000)
在与telnet连接几次之后,我得到了以下警告:
(node:1919) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit
(node:1919) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 unpipe listeners added. Use emitter.setMaxListeners() to increase limit
(node:1919) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 drain listeners added. Use emitter.setMaxListeners() to increase limit
(node:1919) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added. Use emitter.setMaxListeners() to increase limit
(node:1919) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 finish listeners added. Use emitter.setMaxListeners() to increase limit
我正在考虑可能不是在关闭正在创建的对象,或者是在错误的位置创建了readStream
。但这只是猜测,我添加了readStream.destroy()
,但似乎无济于事。
我确定我在这里想念一些大事,但我不知道是什么。我应该在哪里以及如何关闭流?首先我是不是很糟糕?
答案 0 :(得分:0)
我认为您使用的管道方法不正确,应该是这样
client.pipe(readStream)
readStream.pipe(process.stdout)
client.on('end', () => {
console.log('done')
readStream.destroy()
})
此外,您的自定义流必须是双工的(因为我们从流中读取并写入其中),因此,您还必须实现_write()
方法。