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

查看:175
本文介绍了如何在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?

推荐答案

@substack #node ,新的 streams API在Node v10中的使这更容易:

As @substack corrected me in #node, the new streams API in Node v10 makes this easier:

const Readable = require('stream').Readable;
const s = new Readable();
s._read = () => {}; // redundant? see update below
s.push('your text here');
s.push(null);

...之后你可以自由地管道它或以其他方式将其传递给您的目标消费者。

… after which you can freely pipe it or otherwise pass it to your intended consumer.

它不像 resumer 一样干净-liner,但确实避免了额外的依赖。

It's not as clean as the resumer one-liner, but it does avoid the extra dependency.

更新:在v0.10.26到v9.2.1到目前为止,调用推送 _read ,直接来自REPL提示符的$ c>会因未实现异常而崩溃。不会在函数或脚本中崩溃。如果不一致让你感到紧张,请包含 noop 。)

(Update: in v0.10.26 through v9.2.1 so far, a call to push directly from the REPL prompt will crash with a not implemented exception if you didn't set _read. It won't crash inside a function or a script. If inconsistency makes you nervous, include the noop.)

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

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