我正在使用一个库,ya-csv,期望文件或流作为输入,但我有一个字符串。
如何将该字符串转换为节点中的流?
我正在使用一个库,ya-csv,期望文件或流作为输入,但我有一个字符串。
如何将该字符串转换为节点中的流?
当前回答
这有一个模块:https://www.npmjs.com/package/string-to-stream
var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there'
其他回答
下面是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...')
这有一个模块:https://www.npmjs.com/package/string-to-stream
var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there'
编辑: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()
只需创建一个流模块的新实例,并根据您的需要定制它:
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');
不要用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'事件不会被触发(流接口不需要)。