js流的内容读入字符串变量

js流的内容读入字符串变量

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

问题描述

限时删除!!

我正在入侵使用 smtp-protocol 来捕获SMTP的Node程序发送电子邮件并处理邮件数据.该库将邮件数据作为流提供,但我不知道如何将其转换为字符串.

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 })将其写入stdout,但正如我所说,我需要将流数据存储在字符串中,一旦流结束,就可以使用它.

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?

推荐答案

关键是使用 data end 事件https://nodejs.org/api/stream.html#stream_visible_streams"rel =" noreferrer>可读流.听这些事件:

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流的内容读入字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 20:56