I am trying to deal with streams in node.js, read the stream-handbook and some kind of porridge remained in my head (I decided to go through stream-adventure and there is such a task:

It is necessary to read data from stdin and output to stdout in upperCase.

I did this:

process.stdin.on('readable', function(){ var buf = process.stdin.read(); if(buf){ process.stdout.write(buf.toString().toUpperCase()); } }) 

But I would like to do the same through the pipe. I tried to do through an additional readable stream, in which I already pushed the already enlarged letters, which I linked already with stdout. Something like that:

 var stream = require('stream'); var red = new stream.Readable(); process.stdin.on('readable', function(){ var buf = process.stdin.read(); if(buf){ red.push(buf.toString().toUpperCase()); } }) red.pipe(process.stdout); 

But an error was thrown, which I do not even know how to catch ( mistake
(source: joxi.ru )

Please tell me how to do this through the pipe without using additional libraries. And I would be very grateful for the sequential scheme of triggering events when data is received in the readable stream.

Updated.

  • error text would not be superfluous - dizballanze pm
  • @dizballanze added - user184754

2 answers 2

Based on documentation

 process.stdin.setEncoding('utf8'); process.stdin.on('readable', function() { var chunk = process.stdin.read(); if (chunk !== null) { process.stdout.write(chunk.toUpperCase()); } }); 

Version node.js 0.12.4, no installed modules, only this code. Works.

  • Yes, I did. At the very beginning of the question almost the same code) Here’s how to do the same, but only through the pipe. - user184754
  • The difference is that when you specify an encoding, you immediately get a string, not a binary buffer. And what have the pipe? He transmits the stream as it is without modification, as I recall? - Qwertiy
  • I saw the difference. I thought that through the pipe you can somehow intercept the stream, modify it and send the modified one. Almost everywhere, the through module is used for such chips and the code looks like this: js process.stdin.pipe(through(function(buf, enc, cb){ //code changed buf}).pipe(process.stdout); As I understand it, This module works on the basis of duplex streams, which, in turn, are based on simple readable and writable streams. So I wanted to do it through a pipe) I just wanted to understand all these things, but I never really found an explanation for these fundamental things ( - user184754

here it is recommended to return to node version 0.10 about this error.

and the following comment recommends removing npm_modules and then running npm install , but this is probably not about your situation.