我正在使用一个库,ya-csv,期望文件或流作为输入,但我有一个字符串。
如何将该字符串转换为节点中的流?
我正在使用一个库,ya-csv,期望文件或流作为输入,但我有一个字符串。
如何将该字符串转换为节点中的流?
当前回答
从节点10.17,流。Readable有一个from方法,可以轻松地从任何可迭代对象(包括数组字面值)创建流:
const { Readable } = require("stream")
const readable = Readable.from(["input string"])
readable.on("data", (chunk) => {
console.log(chunk) // will be called once with `"input string"`
})
请注意,至少在10.17和12.3之间,字符串本身是一个可迭代对象,因此Readable.from("input string")可以工作,但会为每个字符触发一个事件。Readable.from(["input string"])将为数组中的每一项触发一个事件(在本例中为一项)。
还要注意,在以后的节点中(可能是12.3,因为文档说函数在那时已经改变了),不再需要将字符串包装到数组中。
https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options
其他回答
从节点10.17,流。Readable有一个from方法,可以轻松地从任何可迭代对象(包括数组字面值)创建流:
const { Readable } = require("stream")
const readable = Readable.from(["input string"])
readable.on("data", (chunk) => {
console.log(chunk) // will be called once with `"input string"`
})
请注意,至少在10.17和12.3之间,字符串本身是一个可迭代对象,因此Readable.from("input string")可以工作,但会为每个字符触发一个事件。Readable.from(["input string"])将为数组中的每一项触发一个事件(在本例中为一项)。
还要注意,在以后的节点中(可能是12.3,因为文档说函数在那时已经改变了),不再需要将字符串包装到数组中。
https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options
在coffee-script:
class StringStream extends Readable
constructor: (@str) ->
super()
_read: (size) ->
@push @str
@push null
使用它:
new StringStream('text here').pipe(stream1).pipe(stream2)
不要用Jo Liss的简历回答。这在大多数情况下都是可行的,但在我的案例中,它却让我花了4或5个小时去寻找漏洞。不需要第三方模块来做这件事。
新回答:
var Readable = require('stream').Readable
var s = new Readable()
s.push('beep') // the string you want
s.push(null) // indicates end-of-file basically - the end of the stream
这应该是一个完全兼容的可读流。有关如何正确使用流的更多信息,请参阅这里。
旧的回答: 只需要使用本地PassThrough流:
var stream = require("stream")
var a = new stream.PassThrough()
a.write("your string")
a.end()
a.pipe(process.stdout) // piping will work as normal
/*stream.on('data', function(x) {
// using the 'data' event works too
console.log('data '+x)
})*/
/*setTimeout(function() {
// you can even pipe after the scheduler has had time to do other things
a.pipe(process.stdout)
},100)*/
a.on('end', function() {
console.log('ended') // the end event will be called properly
})
注意,'close'事件不会被触发(流接口不需要)。
正如@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。)
下面是TypeScript中的一个简洁的解决方案:
import { Readable } from 'stream'
class ReadableString extends Readable {
private sent = false
constructor(
private str: string
) {
super();
}
_read() {
if (!this.sent) {
this.push(Buffer.from(this.str));
this.sent = true
}
else {
this.push(null)
}
}
}
const stringStream = new ReadableString('string to be streamed...')