简体   繁体   中英

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

I am facing difficulties taking input in Javascript. I use nodejs to run js files using the following command:

node filename.js

Can someone tell me all the ways in which I can input a 2D matrix from the console?

Also, why is it so difficult in JS? I am looking for a simple method like gets() or something equivalent of cin in C++.

You can useprocess.stdin which read data from your standard input as a stream, which is roughly equivalent to 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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