简体   繁体   English

如何在 javascript (node.js) 中通过控制台输入?

[英]How to take input via console in javascript (node.js)?

I am facing difficulties taking input in Javascript.我在 Javascript 中输入时遇到困难。 I use nodejs to run js files using the following command:我使用 nodejs 使用以下命令运行 js 文件:

node filename.js

Can someone tell me all the ways in which I can input a 2D matrix from the console?有人能告诉我从控制台输入 2D 矩阵的所有方式吗?

Also, why is it so difficult in JS?另外,为什么在 JS 中这么难? I am looking for a simple method like gets() or something equivalent of cin in C++.我正在寻找一个简单的方法,比如 get() 或 C++ 中的 cin 等价物。

You can useprocess.stdin which read data from your standard input as a stream, which is roughly equivalent to C++ cin .您可以使用process.stdin从标准输入中读取数据作为流,这大致相当于 C++ cin

process.stdin.on('readable', () => {
  let data;
  while ((data = process.stdin.read()) !== null) {
    try {
      let obj = JSON.parse(data);
      console.log(obj[1][0])  // -> 3
    } catch (e) {
      console.log('Not a 2D Matrix')
      continue;
    }
  }
});

node index.js
foo
Not a 2D Matrix
[[1, 2], [3, 4], [5, 6]]
3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM