30

I saw this for lots of other languages but not JavaScript.

I'm trying to do problems like: this (codechef.com) and of course the programs need to be able to read standard in like C++ and other languages do.

EDIT: Thanks for the answers. The primary reason I want this functionality is so I can answer the questions on CodeChef; Codechef sends multiple inputs to the files/programs that are the answers (and of course the programs have to respond in the required way for the answer to be correct).

1
  • Hey, I came here from CC too! Commented Nov 18 at 1:06

5 Answers 5

24

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
Sign up to request clarification or add additional context in comments.

Comments

8

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.

1 Comment

Input can come from anywhere in the DOM if the environment is a browser. He probably meant NodeJS environment.
4

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.

1 Comment

If you want to use it in Nodejs, you should require it at first; otherwise it raise and exception which tells "readline is not defined". But this pattern is runnable in D8.
1

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.