我在下面的链接中找到了答案,但在使用他的代码的固定版本后,它也没有工作。它只返回数据,但不是if语句中写入的日志。如果数据与字符串匹配,那么我想执行某个任务,我也尝试过toString()。
How to compare input from process.stdin to string in NodeJS?
我的代码
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')
})
他的修复'代码
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);
});
答案 0 :(得分:1)
如果你是console.log chunk,你会注意到它添加了换行符。所以你需要做的是用换行符分割字符串并检查第一个元素。
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);
});
或者您可以使用npm模块linebyline来简化:
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);
})