1

I'm new to NodeJS and coding in general and while looking for answers to read the contents of a Node.js stream into a string variable on StackOverflow I came across this answer: https://stackoverflow.com/a/63361543/15144023

The following code can be seen in the answer:

// lets have a ReadableStream as a stream variable

const chunks = [];

for await (let chunk of stream) {
    chunks.push(chunk)
}

const buffer  = Buffer.concat(chunks);
const str = buffer.toString("utf-8")

(credit to Traycho Ivanov for the answer)

I get "Unexpected reserved word" in the await word and I can' understand how to fix it and how to actually use it. Unfortunately being new on StackOverflow doesn't allow me to comment on the answer, being the reason I used this approach.

1 Answers1

1

I assume that the original answer is just a snippet and not the full solution, as you can only use for await loop inside an async function. Here's a full working example with the for await wrapped in an anonymous async function. Note I've also initialized a mock stream.

const { Readable } = require('stream');

// Mocking a stream for demo purposes
const stream = Readable.from(Buffer.from('this is a test string', 'utf-8'));

(async function() {
  const chunks = [];

  for await (let chunk of stream) {
      chunks.push(chunk)
  }

  const buffer  = Buffer.concat(chunks);
  const str = buffer.toString("utf-8")
  console.log(str);
})();
Josh Aguilar
  • 2,111
  • 1
  • 10
  • 17
  • Okay, that makes sense, I tried a similar approach before but wasn't understanding how to get anything out of it. I wasn't calling it nor creating a stream. That was very helpful, thank you!! My goal is to save the outputs of data that is originally going to stdout into variables so I can decide when to send them to stdout or put them in a file. I have some ideas to try out with this function, do you think there could be a better approach? (P.S. I'm sorry I can't upvote yet :( ) – Luís Prates Feb 04 '21 at 17:39
  • No worries. Glad I could help and welcome to SO! I'd probably need to know more about your use case to be able to give an opinion but this option seems ok if you want to check all of the stream contents once. However, if you want to progressively check the the stream contents you can use `stream.on('data', callbackFunc)` and do the check inside `callbackFunc`. – Josh Aguilar Feb 04 '21 at 19:06