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

一笑奈何 提交于 2019-12-25 03:36:11

问题


I'm using nodeJS and I want to be able to pass it commands via stdin. To do this I'm using process.stdin. Ideally I'd have a giant switch with various command strings like "load" or "stop", but I can't get the comparison to work. I've tried slicing out newlines, converting to strings, etc. Can't figure this out, though it seems like it should be fairly simple.

Below is the code I've been trying to get to work:

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")
    console.log("got it!");

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

});

回答1:


Typically if you want to read newline-delimited input from stdin, it's easiest to use the built-in readline module.

However for your original code, the problem most likely is either in the chunking of the input and/or that the newline is also captured, so you'd eventually have to either strip it off or change your conditional to something like if(chunk == "expectedinput\n") (assuming you have buffered enough input data to see the newline).



来源:https://stackoverflow.com/questions/30156588/how-to-compare-input-from-process-stdin-to-string-in-nodejs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!