【问题标题】:insert conditional statements in readable streams of process.stdin在 process.stdin 的可读流中插入条件语句
【发布时间】:2017-02-01 17:45:45
【问题描述】:

好吧,我正在尝试将一个简单的 if 语句传递给 NodeJS 中的 process.stdin 可读流。但这似乎不起作用。这是代码:

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null && chunk == 'foo') {
    process.stdout.write('true\n');
} else if (chunk !== null) {
    process.stdout.write('false\n');
}

有谁知道,我在这里做错了什么?我也试过chunk == 'foo\n',但是没有运气。它唯一有效的时候是我将块值设置为一个数字,比如chunk == 10

【问题讨论】:

  • “它似乎没有 [to be] 工作”是什么意思?输入是什么? chunk 的实际值是多少? (当你做console.log(chunk)时你会得到什么)?
  • 当您在 process.stdin 上键入 'foo' 时,该块为 <Buffer 66 6f 6f 0a>,因此您可以使用 if(chunk.toString()==='foo\n'),它给出了 true

标签: javascript node.js stdin


【解决方案1】:

这里的问题是块是缓冲区类型,而不是字符串。您可以使用 chunk.toString() 使其成为字符串,然后将其与 foo\n(如果在 linux 上)或 foo\r\n(如果在 windows 上)进行比较,它会工作

所以你的代码看起来像这样:

process.stdin.on('readable', function() {
  var chunk = process.stdin.read();
  if (chunk !== null && chunk.toString() == 'foo\n' || 'foo\r\n') {
    process.stdout.write('true\n');
  } else if (chunk !== null) {
    process.stdout.write('false\n');
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-04-11
    • 2014-11-28
    • 2018-03-24
    • 2015-07-14
    相关资源
    最近更新 更多