我正在入侵一个Node程序,该程序使用SMTP协议捕获SMTP电子邮件并对邮件数据采取行动。库将邮件数据作为流提供,但我不知道如何将其转换为字符串。
我目前正在用stream.pipe(process. pipe)将其写入标准输出。stdout, {end: false}),但正如我所说的,我需要一个字符串中的流数据,一旦流结束,我就可以使用它。
我如何收集所有的数据从一个Node.js流到一个字符串?
我正在入侵一个Node程序,该程序使用SMTP协议捕获SMTP电子邮件并对邮件数据采取行动。库将邮件数据作为流提供,但我不知道如何将其转换为字符串。
我目前正在用stream.pipe(process. pipe)将其写入标准输出。stdout, {end: false}),但正如我所说的,我需要一个字符串中的流数据,一旦流结束,我就可以使用它。
我如何收集所有的数据从一个Node.js流到一个字符串?
当前回答
简单易用的流行(每周超过500万次下载)和轻量级的get-stream库:
https://www.npmjs.com/package/get-stream
const fs = require('fs');
const getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream)); //output is string
})();
其他回答
希望这比上面的答案更有用:
var string = '';
stream.on('data',function(data){
string += data.toString();
console.log('stream data ' + part);
});
stream.on('end',function(){
console.log('final output ' + string);
});
请注意,字符串连接并不是收集字符串部分的最有效方法,但使用它是为了简单(也许您的代码并不关心效率)。
此外,对于非ascii文本,这段代码可能会产生不可预测的失败(它假设每个字符都适合一个字节),但也许您也不关心这一点。
在我的例子中,响应头的内容类型是content - type: text/plain。所以,我已经从Buffer读取了数据:
let data = [];
stream.on('data', (chunk) => {
console.log(Buffer.from(chunk).toString())
data.push(Buffer.from(chunk).toString())
});
(这个答案是多年前的,当时它是最好的答案。下面有一个更好的答案。我没有跟上node.js,我不能删除这个答案,因为它被标记为“正确的这个问题”。如果你想按下,你想让我做什么?)
关键是使用可读流的数据和结束事件。听下面这些事件:
stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });
当您收到数据事件时,将新的数据块添加到为收集数据而创建的Buffer中。
当您接收到结束事件时,如果需要,将完成的Buffer转换为字符串。那就做你该做的事。
像减流器这样的东西怎么样?
下面是一个使用ES6类的例子如何使用一个。
var stream = require('stream')
class StreamReducer extends stream.Writable {
constructor(chunkReducer, initialvalue, cb) {
super();
this.reducer = chunkReducer;
this.accumulator = initialvalue;
this.cb = cb;
}
_write(chunk, enc, next) {
this.accumulator = this.reducer(this.accumulator, chunk);
next();
}
end() {
this.cb(null, this.accumulator)
}
}
// just a test stream
class EmitterStream extends stream.Readable {
constructor(chunks) {
super();
this.chunks = chunks;
}
_read() {
this.chunks.forEach(function (chunk) {
this.push(chunk);
}.bind(this));
this.push(null);
}
}
// just transform the strings into buffer as we would get from fs stream or http request stream
(new EmitterStream(
["hello ", "world !"]
.map(function(str) {
return Buffer.from(str, 'utf8');
})
)).pipe(new StreamReducer(
function (acc, v) {
acc.push(v);
return acc;
},
[],
function(err, chunks) {
console.log(Buffer.concat(chunks).toString('utf8'));
})
);
你觉得这个怎么样?
async function streamToString(stream) {
// lets have a ReadableStream as a stream variable
const chunks = [];
for await (const chunk of stream) {
chunks.push(Buffer.from(chunk));
}
return Buffer.concat(chunks).toString("utf-8");
}