node.js - 如何将 process.stdin 的输入与字符串进行比较? Node.js

标签 node.js process

我在下面的链接中找到了答案,但是在使用他的代码的固定版本后,它也不起作用。它只返回数据,但不返回 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);

});

最佳答案

如果你console.log block ,你会注意到它添加了一个换行符。所以你需要做的就是用换行符分割字符串并检查第一个元素。

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);
 })

关于node.js - 如何将 process.stdin 的输入与字符串进行比较? Node.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48066896/

相关文章:

javascript - 将文件中的对象属性随机分配给 inline-css

javascript - net.request 发布数据不工作

Python的multiprocessing.Queue + Process : Properly terminating both programs

linux - Linux 进程空闲时间

node.js - 如何在 OpenShift 环境中运行 npm 模块 node-inspector?

javascript - 使用 node.js 更新和删除按钮

node.js - eslint-plugin-security 在检查 Mongoose exec() 方法时抛出类型错误

c - 是什么导致我的程序挂起并且无法正常退出? (管道,读取系统调用,while 循环)

node.js - nodejs .exe 应用程序在 UWP 中打开后立即崩溃

android - SharedPreferences 的 MODE_MULTI_PROCESS 是否不如 MODE_PRIVATE 安全