Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/423.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在流程中添加条件。stdin';什么是可读事件?_Javascript_Node.js_Stdin - Fatal编程技术网

Javascript 如何在流程中添加条件。stdin';什么是可读事件?

Javascript 如何在流程中添加条件。stdin';什么是可读事件?,javascript,node.js,stdin,Javascript,Node.js,Stdin,我正在尝试将一个简单的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) {

我正在尝试将一个简单的
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
值设置为一个数字时,它才会起作用,比如
chunk==10
您可以使用.prompt()()方法@Siam这里的问题是
chunk
缓冲区类型,而不是
字符串。您可以使用
chunk.toString()
将其设置为字符串,然后将其与
中的“foo\n”
进行比较,这样就可以了

因此,您的代码如下所示:

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


确保使用的比较字符串与输入相同。例如,在上述情况下,在基于windows的系统上,新行字符可以是
CRLF
\r\n
,而在基于Unix的系统上,新行字符可以是
LF
\n
。因此,如果在windows上

是的,我已经尝试过了,但没有工作,请尝试使用
“foo\r\n”
进行比较。我不知道怎么了(它对我有用…可能还有其他问题…你是否尝试过使用“数据”事件?而且不“可读”,你使用的是node.js的哪个版本?是的,我使用了。但是“数据”也有同样的问题。:/我使用的是NodeJS的7.0.0版。你能记录chunk.toString的值吗(首先使用任何
转义
编码URI
)这将告诉您在windows系统上输入和匹配字符串之间的区别,新行可以是
CRLF
\r\n
,而在基于unix的系统上,它的
LF
\n
。如果在windows上,请尝试使用
\r\n