How do I get console input in javascript?

前端 未结 4 2118
独厮守ぢ
独厮守ぢ 2020-12-04 17:21

I\'m currently using spidermonkey to run my JavaScript code. I\'m wondering if there\'s a function to get input from the console similar to how Python does this:

<         


        
4条回答
  •  情书的邮戳
    2020-12-04 17:53

    You can try something like process.argv, that is if you are using node.js to run the program.
    console.log(process.argv) => Would print an array containing

    [                                                                                                                                                                                          
      '/usr/bin/node',                                                                                                                                                                         
      '/home/user/path/filename.js',                                                                                                                                            
      'your_input'                                                                                                                                                                                   
    ]
    

    You get the user provided input via array index, i.e., console.log(process.argv[3]) This should provide you with the input which you can store.


    Example:

    var somevariable = process.argv[3]; // input one
    var somevariable2 = process.argv[4]; // input two
    
    console.log(somevariable);
    console.log(somevariable2);
    

    If you are building a command-line program then the npm package yargs would be really helpful.

提交回复
热议问题