如何将 Node.js 流的内容读入字符串变量? [英] How do I read the contents of a Node.js stream into a string variable?

查看:22
本文介绍了如何将 Node.js 流的内容读入字符串变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在破解一个使用 smtp-protocol 的 Node 程序 捕获 SMTP 电子邮件并对邮件数据进行操作.该库以流的形式提供邮件数据,我不知道如何将其转换为字符串.

I'm hacking on a Node program that uses smtp-protocol to capture SMTP emails and act on the mail data. The library provides the mail data as a stream, and I don't know how to get that into a string.

我目前正在使用 stream.pipe(process.stdout, { end: false }) 将它写入标准输出,但正如我所说,我需要字符串中的流数据,这我可以在流结束后使用.

I'm currently writing it to stdout with stream.pipe(process.stdout, { end: false }), but as I said, I need the stream data in a string instead, which I can use once the stream has ended.

如何将 Node.js 流中的所有数据收集到一个字符串中?

How do I collect all the data from a Node.js stream into a string?

推荐答案

(这个答案是几年前的,当时是最好的答案.现在在这个下面有更好的答案.我没有跟上 node.js,我不能删除这个答案,因为它被标记为在这个问题上是正确的".如果你想向下点击,你想让我做什么?)

(This answer is from years ago, when it was the best answer. There is now a better answer below this. I haven't kept up with node.js, and I cannot delete this answer because it is marked "correct on this question". If you are thinking of down clicking, what do you want me to do?)

关键是使用 dataend 事件的 可读流.收听这些事件:

The key is to use the data and end events of a Readable Stream. Listen to these events:

stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });

当您收到 data 事件时,将新的数据块添加到为收集数据而创建的缓冲区中.

When you receive the data event, add the new chunk of data to a Buffer created to collect the data.

当您收到 end 事件时,如有必要,将完成的 Buffer 转换为字符串.然后做你需要做的事情.

When you receive the end event, convert the completed Buffer into a string, if necessary. Then do what you need to do with it.

这篇关于如何将 Node.js 流的内容读入字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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