我正在入侵一个Node程序,该程序使用SMTP协议捕获SMTP电子邮件并对邮件数据采取行动。库将邮件数据作为流提供,但我不知道如何将其转换为字符串。
我目前正在用stream.pipe(process. pipe)将其写入标准输出。stdout, {end: false}),但正如我所说的,我需要一个字符串中的流数据,一旦流结束,我就可以使用它。
我如何收集所有的数据从一个Node.js流到一个字符串?
我正在入侵一个Node程序,该程序使用SMTP协议捕获SMTP电子邮件并对邮件数据采取行动。库将邮件数据作为流提供,但我不知道如何将其转换为字符串。
我目前正在用stream.pipe(process. pipe)将其写入标准输出。stdout, {end: false}),但正如我所说的,我需要一个字符串中的流数据,一旦流结束,我就可以使用它。
我如何收集所有的数据从一个Node.js流到一个字符串?
当前回答
这对我来说是有效的,并且基于Node v6.7.0文档:
let output = '';
stream.on('readable', function() {
let read = stream.read();
if (read !== null) {
// New stream data is available
output += read.toString();
} else {
// Stream is now finished when read is null.
// You can callback here e.g.:
callback(null, output);
}
});
stream.on('error', function(err) {
callback(err, null);
})
其他回答
以上这些方法对我都没用。我需要使用Buffer对象:
const chunks = [];
readStream.on("data", function (chunk) {
chunks.push(chunk);
});
// Send the buffer or you can put it into a var
readStream.on("end", function () {
res.send(Buffer.concat(chunks));
});
最简洁的解决方案可能是使用“string-stream”包,它将流转换为带有承诺的字符串。
const streamString = require('stream-string')
streamString(myStream).then(string_variable => {
// myStream was converted to a string, and that string is stored in string_variable
console.log(string_variable)
}).catch(err => {
// myStream emitted an error event (err), so the promise from stream-string was rejected
throw err
})
简单易用的流行(每周超过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
})();
(这个答案是多年前的,当时它是最好的答案。下面有一个更好的答案。我没有跟上node.js,我不能删除这个答案,因为它被标记为“正确的这个问题”。如果你想按下,你想让我做什么?)
关键是使用可读流的数据和结束事件。听下面这些事件:
stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });
当您收到数据事件时,将新的数据块添加到为收集数据而创建的Buffer中。
当您接收到结束事件时,如果需要,将完成的Buffer转换为字符串。那就做你该做的事。
流没有简单的. tostring()函数(我理解),也没有类似于. tostringasync (cb)函数(我不理解)的东西。
所以我创建了自己的helper函数:
var streamToString = function(stream, callback) {
var str = '';
stream.on('data', function(chunk) {
str += chunk;
});
stream.on('end', function() {
callback(str);
});
}
// how to use:
streamToString(myStream, function(myStr) {
console.log(myStr);
});