sweetroll
sweetroll

Reputation: 341

How to compare input from process.stdin to string? Node.js

I found an answer at the link below, but after using the fixed version of his code it's not working either. It just gives the data back but not the log written in the if statement. If the data matches a string then I want to perform a certain task, I've also tried toString().

How to compare input from process.stdin to string in NodeJS?

My code

process.stdin.setEncoding('utf8');

process.stdin.on('readable', () => {
    const data = process.stdin.read()
    if (data == 'expected\n') {
        process.stdout.write('worked')
    }
})

process.stdin.on('end', () => {
    process.stdout.write('end')
})

His 'fixed' code

process.stdin.setEncoding('utf8');

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();

  if(chunk === null)
    return;

//i've tried this as well, to no avail
//chunk = chunk.toString();

  if(chunk == "expectedinput\n")
    console.log("got it!");

process.stdout.write('data: ' + chunk);

});

Upvotes: 2

Views: 2143

Answers (1)

SunriseM
SunriseM

Reputation: 995

If you console.log chunk you will notice that it adds a newline. so what you need to do is split the string by newlines and check the first element.

process.stdin.setEncoding('utf8');

var os = require('os');


process.stdin.on('readable', function() {
  var chunk = process.stdin.read();

  if(chunk === null)
    return;

  chunk = chunk.split(os.EOL);

  if(chunk[0] == "expectedinput")
    console.log("got it!");

  process.stdout.write('data: ' + chunk);
});

or you can use npm module linebyline that makes it easier:

var readline = require('linebyline');
var rl = readline.createInterface({
   input: process.stdin,
   output: process.stdout,
   terminal: false
 });

 rl.on('line', function(line){
    if(line == "expectedinput") console.log("got it!");
    console.log(line);
 })

Upvotes: 2

Related Questions