Javascript 如何从 Node.Js 中的字符串创建流?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12755997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create streams from string in Node.Js?
提问by pathikrit
采纳答案by Fizker
From node 10.7, stream.Readable have a from
method to easily create streams from any iterable (which includes array literals):
从节点 10.7 开始,stream.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"`
})
Note that at least between 10.7 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).
请注意,至少在 10.7 和 12.3 之间,字符串本身是可迭代的,因此Readable.from("input string")
可以工作,但每个字符发出一个事件。Readable.from(["input string"])
将为数组中的每一项(在本例中为一项)发出一个事件。
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.
另请注意,在以后的节点中(可能是 12.3,因为文档说当时函数已更改),不再需要将字符串包装在数组中。
https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options
https://nodejs.org/api/stream.html#stream_stream_readable_from_iterable_options
回答by Garth Kidd
As @substackcorrected me in #node, the new streams APIin Node v10 makes this easier:
作为@substack纠正我#node,新的流API在节点V10使这更容易:
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 pipeit or otherwise pass it to your intended consumer.
……之后,您可以自由地将其通过管道传输或以其他方式将其传递给您的目标消费者。
It's not as clean as the resumerone-liner, but it does avoid the extra dependency.
它不像恢复单行那样干净,但它确实避免了额外的依赖。
(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
.)
(更新:到目前为止,在 v0.10.26 到 v9.2.1 中,如果您没有设置,push
直接从 REPL 提示调用将崩溃并出现not implemented
异常_read
。它不会在函数或脚本内崩溃。如果不一致使您紧张,包括noop
.)
回答by B T
Do not use Jo Liss's resumer answer. It will work in most cases, but in my case it lost me a good 4 or 5 hours bug finding. There is no need for third party modules to do this.
不要使用 Jo Liss 的简历答案。它在大多数情况下都可以工作,但在我的情况下,它让我失去了 4 或 5 个小时的错误查找时间。不需要第三方模块来执行此操作。
NEW ANSWER:
新答案:
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
This should be a fully compliant Readable stream. See herefor more info on how to use streams properly.
这应该是一个完全兼容的可读流。有关如何正确使用流的更多信息,请参见此处。
OLD ANSWER: Just use the native PassThrough 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
})
Note that the 'close' event is not emitted (which is not required by the stream interfaces).
请注意,不会发出 'close' 事件(流接口不需要)。
回答by zemirco
Just create a new instance of the stream
module and customize it according to your needs:
只需创建stream
模块的新实例并根据您的需要对其进行自定义:
var Stream = require('stream');
var stream = new Stream();
stream.pipe = function(dest) {
dest.write('your string');
return dest;
};
stream.pipe(process.stdout); // in this case the terminal, change to ya-csv
or
或者
var Stream = require('stream');
var stream = new Stream();
stream.on('data', function(data) {
process.stdout.write(data); // change process.stdout to ya-csv
});
stream.emit('data', 'this is my string');
回答by Jo Liss
Edit:Garth's answeris probably better.
编辑:加思的答案可能更好。
My old answer text is preserved below.
我的旧答案文本保留在下面。
To convert a string to a stream, you can use a paused throughstream:
将一个字符串转换成流,你可以使用一个暂停通过流:
through().pause().queue('your string').end()
Example:
例子:
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()
回答by Lori
There's a module for that: https://www.npmjs.com/package/string-to-stream
有一个模块:https: //www.npmjs.com/package/string-to-stream
var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there'
回答by xinthink
in coffee-script:
在咖啡脚本中:
class StringStream extends Readable
constructor: (@str) ->
super()
_read: (size) ->
@push @str
@push null
use it:
用它:
new StringStream('text here').pipe(stream1).pipe(stream2)
回答by Philippe T.
Another solution is passing the read function to the constructor of Readable (cf doc stream readeable options)
另一种解决方案是将 read 函数传递给 Readable 的构造函数(参见 doc stream readeable options)
var s = new Readable({read(size) {
this.push("your string here")
this.push(null)
}});
you can after use s.pipe for exemple
例如,您可以在使用 s.pipe 之后
回答by Chris Allen Lane
I got tired of having to re-learn this every six months, so I just published an npm module to abstract away the implementation details:
我厌倦了每六个月重新学习一次,所以我刚刚发布了一个 npm 模块来抽象出实现细节:
https://www.npmjs.com/package/streamify-string
https://www.npmjs.com/package/streamify-string
This is the core of the module:
这是模块的核心:
const Readable = require('stream').Readable;
const util = require('util');
function Streamify(str, options) {
if (! (this instanceof Streamify)) {
return new Streamify(str, options);
}
Readable.call(this, options);
this.str = str;
}
util.inherits(Streamify, Readable);
Streamify.prototype._read = function (size) {
var chunk = this.str.slice(0, size);
if (chunk) {
this.str = this.str.slice(size);
this.push(chunk);
}
else {
this.push(null);
}
};
module.exports = Streamify;
str
is the string
that must be passed to the constructor upon invokation, and will be outputted by the stream as data. options
are the typical options that may be passed to a stream, per the documentation.
str
是string
在调用时必须传递给构造函数的 ,并将由流作为数据输出。根据文档options
,是可以传递给流的典型选项。
According to Travis CI, it should be compatible with most versions of node.
根据 Travis CI,它应该与大多数版本的节点兼容。
回答by Russell Briggs
Heres a tidy solution in TypeScript:
这是 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...')