0

The program below simply reads a string and outputs it. When I run this on cmd, the program doesn't print out the string. It keeps reading inputs until I terminate with Ctrl+C. How do I tell the program when my input string is over, so it can print the output?

var concat=require('concat-stream');
var str=[];
process.stdin.pipe(concat(function(buff){
    console.log(buff.toString());
}));

2 Answers 2

3

concat-stream is waiting to receive a finish event. In your example that will happen when you close stdin. If you’re running this in a shell you can close stdin by pressing Ctrl+D. If you’re piping something to your process, make sure it closes its stdout when it’s done.

If you’re trying to make your script interactive in the shell, try split:

process.stdin
  .pipe(require('split')())
  .on('data', function (line) {
    console.log('got “%s”', line);
  });
Sign up to request clarification or add additional context in comments.

Comments

1

Obviously the answer by Todd Yandell is the right one, and I have already upvoted it, but I wanted to add that besides split, you may also consider the use of through which creates a sort of transformer and it would also work in a interactive way, since it is not an aggregation pipe.

Like this example in which everything you write in the standard input gets uppercased in standard output interactively:

var through = require('through');

function write(buffer){
    var text = buffer.toString();
    this.queue(text.toUpperCase());
}

function end(){
    this.queue(null);
}

var transform = through(write, end);
process.stdin.pipe(transform).pipe(process.stdout);

You may even combine it with split by doing:

process.stdin
       .pipe(split())
       .pipe(transform)
       .pipe(process.stdout);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.