Is there a way to read standard input with JavaScript?

社会主义新天地 提交于 2019-11-28 21:18:34
Cameron

It depends on the environment that your JavaScript is executing in.

In the browser, there is no standard input (the browser isn't a console). The input would come generally from some textbox element in a form on the page.

If you're using something like Rhino, then you can import the standard Java I/O classes and read from stdin that way (see the second example no longer on the wiki).

If you use node to act as an interpreter in the terminal, you can use this:

---- name.js ----
var readline = require('readline');

var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout

});

rl.question(">>What's your name?  ", function(answer) {
   console.log("Hello " + answer);
   rl.close();
});

----- terminal ----
node name.js

Use just readline()

var a = readLine();

the value which you give input will be stored in variable a.

readline() : Reads a single line of input from stdin, returning it to the caller. You can use this to create interactive shell programs in JavaScript.

It's not in the ECMAScript (standardized version of JavaScript) standard library. However, some implementations of JavaScript do include it. For example, CommonJS, which is used by several out-of-the-browser JavaScript environments, has a system.stdin property. Rhino can use Java's standard input classes.

If you're just trying to practice programming, you can use a textarea as a substitute for standard input.

In some environments like interviewstreet's, they provide you with a function in which all the input is coming as an argument in form of a string.

All of the input at once.

Then you have to parse that input to get various tokens out of that string.

After this you should be good to write the code further.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!