我正在使用一个库,ya-csv,期望文件或流作为输入,但我有一个字符串。
如何将该字符串转换为节点中的流?
我正在使用一个库,ya-csv,期望文件或流作为输入,但我有一个字符串。
如何将该字符串转换为节点中的流?
当前回答
在coffee-script:
class StringStream extends Readable
constructor: (@str) ->
super()
_read: (size) ->
@push @str
@push null
使用它:
new StringStream('text here').pipe(stream1).pipe(stream2)
其他回答
这有一个模块:https://www.npmjs.com/package/string-to-stream
var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there'
正如@substack在#node中纠正了我,node v10中的新streams API使这更容易:
const Readable = require('stream').Readable;
const s = new Readable();
s._read = () => {}; // redundant? see update below
s.push('your text here');
s.push(null);
之后,你可以自由地将它输送给你的目标客户。
它不像resumer一行程序那样简洁,但它确实避免了额外的依赖关系。
(更新:在v0.10.26到v9.2.1到目前为止,如果你没有设置_read,直接从REPL提示符调用push将会崩溃,并出现一个未实现的异常。它不会在函数或脚本中崩溃。如果前后矛盾让你紧张,那就加上noop。)
编辑:Garth的答案可能更好。
我以前的答案文本保存在下面。
要将字符串转换为流,可以使用pause through流:
through().pause().queue('your string').end()
例子:
var through = require('through')
// Create a paused stream and buffer some data into it:
var stream = through().pause().queue('your string').end()
// Pass stream around:
callback(null, stream)
// Now that a consumer has attached, remember to resume the stream:
stream.resume()
另一个解决方案是将read函数传递给Readable的构造函数(cf doc stream Readable options)
var s = new Readable({read(size) {
this.push("your string here")
this.push(null)
}});
例如,你可以使用s.pipe
在coffee-script:
class StringStream extends Readable
constructor: (@str) ->
super()
_read: (size) ->
@push @str
@push null
使用它:
new StringStream('text here').pipe(stream1).pipe(stream2)