Darth.Vader
Darth.Vader

Reputation: 6271

Write NodeJS stream into a string synchronously

I know that one can synchronously read a file in NodeJS like this:

var fs = require('fs');
var content = fs.readFileSync('myfilename');
console.log(content);

I am instead interested in being able to read the contents from a stream into a string synchronously. Thoughts?

Upvotes: 1

Views: 1334

Answers (1)

jfriend00
jfriend00

Reputation: 707238

Streams in node.js are not synchronous - they are event driven. They just aren't synchronous. So, you can't get their results into a string synchronously.

If you have no choice but to use a stream, then you have no choice but to deal with the contents of the stream asynchronously.

If you can change the source of the data to a synchronous source such as the fs.readFileSync() that you show, then you can do that (though generally not recommended for a multi-user server process).

Upvotes: 1

Related Questions