如何将 process.stdin 的输入与 NodeJS 中的字符串进行比较? [英] How to compare input from process.stdin to string in NodeJS?
问题描述
我正在使用 nodeJS,并且我希望能够通过 stdin 向它传递命令.为此,我使用 process.stdin.理想情况下,我有一个带有各种命令字符串的巨大开关,例如加载"或停止",但我无法进行比较.我试过切出换行符,转换为字符串等.无法弄清楚这一点,虽然它看起来应该相当简单.
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);
});
推荐答案
通常,如果您想从 stdin 读取换行符分隔的输入,最容易使用内置的 readline
模块.
Typically if you want to read newline-delimited input from stdin, it's easiest to use the built-in readline
module.
但是,对于您的原始代码,问题很可能在于输入的分块和/或换行符也被捕获,因此您最终必须将其剥离或将条件更改为类似 if(chunk == "expectedinput\n")
(假设您已经缓冲了足够的输入数据以查看换行符).
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).
这篇关于如何将 process.stdin 的输入与 NodeJS 中的字符串进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!