问题
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