如何在 Node.Js 中从字符串创建流? [英] How to create streams from string in Node.Js?

查看:48
本文介绍了如何在 Node.Js 中从字符串创建流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个库,ya-csv,它需要一个文件或一个流作为输入,但我有一个字符串.

I am using a library, ya-csv, that expects either a file or a stream as input, but I have a string.

如何在 Node 中将该字符串转换为流?

How do I convert that string into a stream in Node?

推荐答案

从 node 10.17 开始,stream.Readable 有一个 from 方法可以轻松地从任何可迭代对象(包括数组文字)创建流:

From node 10.17, stream.Readable have a from method to easily create streams from any iterable (which includes array literals):

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"]) 将为数组中的每一项(在本例中为一项)发出一个事件.

Note that at least between 10.17 and 12.3, a string is itself a iterable, so Readable.from("input string") will work, but emit one event per character. Readable.from(["input string"]) will emit one event per item in the array (in this case, one item).

还要注意,在以后的节点中(可能是 12.3,因为文档说当时函数已更改),不再需要将字符串包装在数组中.

Also note that in later nodes (probably 12.3, since the documentation says the function was changed then), it is no longer necessary to wrap the string in an array.

https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options

这篇关于如何在 Node.Js 中从字符串创建流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆