KilimaTango KilimaTango - 4 years ago 110
Node.js Question

insert conditional statements in readable streams of process.stdin

Well, I'm trying to pass a simple if statement to a process.stdin readable stream in NodeJS. But it doesn't seem working. Here's the code :

process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null && chunk == 'foo') {
process.stdout.write('true\n');
} else if (chunk !== null) {
process.stdout.write('false\n');
}


Does anyone know, what am I doing wrong here? I also tried
chunk == 'foo\n'
but, had no luck. The only time it works is when I set chunk value to a number, like
chunk == 10
.

Answer Source

The issue here is that the chunk is of Buffer type, and not a string. You can use chunk.toString() to make it a string, and then compare it with foo\n (if on linux) or foo\r\n (if on windows) and it would work

So your code would look something like this:

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null && chunk.toString() == 'foo\n' || 'foo\r\n') {
    process.stdout.write('true\n');
  } else if (chunk !== null) {
    process.stdout.write('false\n');
  }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download