Stream in NodeJS
Stream in NodeJS
我需要一些帮助来了解流在NodeJS 中的工作方式
我解释说,我需要编写一个模块来调用UNIX进程(带有spawn
),我想将该进程的stdout
重定向到ReadableStream。
我希望这种行为exports
可读流,并允许另一个模块读取它们。
为此,我写了一小段代码:
var spawn = require('child_process').spawn
var Duplex = require('stream').Duplex;
var stream = new Duplex;
var start = function() {
ps = spawn('mycmd', [/*... args ...*/]);
ps.stdout.pipe(stream);
};
exports.stream = stream;
exports.start = start;
但如果我使用这个模块,我会抛出一个异常,说明流没有实现_read方法。
你能帮我解决这个问题吗?
提前谢谢。
[EDIT]我尝试过创建Stream对象的解决方案,但这不起作用,下面是代码:
var spawn = require('child_process').spawn;
var Stream = require('stream');
var ps = null;
var audio = new Stream;
audio.readable = audio.writable = true;
var start = function() {
if(ps == null) {
ps = spawn('mycmd', []);
ps.stdout.pipe(stream);
}
};
var stop = function() {
if(ps) {
ps.kill();
ps = null;
}
};
exports.stream = stream;
exports.start = start;
exports.stop = stop;
但当我试图收听流时,我遇到了一个新的错误:
_stream_readable.js:583
var written = dest.write(chunk);
^
TypeError: Object #<Stream> has no method 'write'
大多数Node的Stream类并不打算直接使用,而是作为自定义类型的基础:
请注意,
stream.Duplex
是一个抽象类,设计用于使用_read(size)
和_write(chunk, encoding, callback)
方法的底层实现进行扩展,就像使用Readable或Writable流类一样。
一个值得注意的例外是stream.PassThrough
,它是一个简单的回声流实现。
var PassThrough = require('stream').PassThrough;
var stream = new PassThrough;
还要注意的是,ps
将是全局的,使其在所有其他模块中都可以直接访问。
如果您只是想使用流,那么您应该执行以下操作:
var stream = new Stream;
stream.readable = stream.writable = true;
双工是为开发人员设计的。它需要实现_read
和_write
等方法
[更新]
好的,您有来自stdout的数据源。您将需要write
功能,使用此功能:
stream.write = function(data){this.emit('data', data);};
相关文章:
- Require in nodejs
- ReadFile in Base64 Nodejs
- What is the reason for cloning the listeners array in nodejs
- Schema.pre in Mongoose modules (NodeJS)
- linkify urls in templates-nodejs
- NodeJS put array in MongoDB doc.validate 不是一个函数
- setTimeout in nodejs - for loops
- 无法在 nodeJS:TypeError 中对用户进行身份验证:无法使用“in”运算符在 fs 中搜索“用户名”
- setInterval in nodejs
- setTimeout in nodejs
- removeListener in the Listener in nodejs
- Stream in NodeJS
- RabbitMQ no ack in nodejs
- NodeJS MSSQL WHERE IN准备的SQL语句
- res.send vs res.locals in nodejs
- cURL post request in Nodejs.
- Adding in Javascript (NodeJS)
- Github Post-Receive Hook in Nodejs
- DRY in Nodejs Express
- Faye Websocket in NodeJS