【问题标题】:How to compare input from process.stdin to string? Node.js如何将 process.stdin 的输入与字符串进行比较?节点.js
【发布时间】:2018-01-02 19:44:35
【问题描述】:

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

});

【问题讨论】:

    标签: node.js process


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答!很抱歉在问题中提出问题,但 readline 模块是异步的吗?
    • 它基于事件,所以当有新输入时它会发出一个事件。你为什么问?。 readline 也被重命名为 linebyline,所以你应该安装它而不是 readline。
    • 感谢您的提示,我正在使用此代码创建一个 p2p 消息传递应用程序,我需要它是 100% 异步的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 1970-01-01
    • 2012-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多