User input with node.js

I have the following Node.js code that behaves strangely:

#!/usr/bin/env node "use strict"; var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function input(prompt) { rl.question(prompt, function (x) { rl.close(); console.log("debug: " + x); return x; }); } function main() { var n = input("Number: "); // console.log("value: " + n); // problematic line } main(); 

I want to emulate Python raw_input , i.e. read a line from the user. After showing the prompt, the program should be blocked until the user presses the Enter key.

If the "problem line" is in the comments, it works, the program waits for input. However, if there are no comments on this line, the program does not wait for input, and n becomes undefined . What for? How to write a function that returns user input?

+5
source share
1 answer

This is because you are waiting for the input to complete until a return is called, which does not work. The problem line is indeed the previous one. First, the input does not return anything, the return statement is the return of the question callback function, but then you seem to misunderstand the thread of execution, as we all do at some point (you will get it pretty quickly after some dead ends up like this)

  • Script loaded
  • You declare and define rl, input and main
  • Main functions
  • You define n as the result of input. And that's where things start to get asynchronously funny.
    • since the question is asynchronous, the launch starts, but does not block the process.
    • returns undefined (while you are still waiting for input)
    • you print that undefined
    • You write something in the input
    • question () finishes its execution and calls the callback (function that you gave as the second parameter)
    • rl closed
    • the callback function returns a string and it is swallowed by emptiness (this is not technical terminology, but just a metaphor)

You can do it as follows:

 #!/usr/bin/env node "use strict"; var readline = require('readline'); var rl = readline.createInterface({ input: process.stdin, output: process.stdout }); function input(prompt, callback) { rl.question(prompt, function (x) { rl.close(); callback(x); }); } function main() { var n = input("Number: ", console.log); } main(); 

If you are new to javascript and node, you can use the learnyounode and node path of the code school, or even if you have the time, money, and opportunity, read Node.js, MongoDB and AngularJS Web Development , by Brad Daily.

+3
source

Source: https://habr.com/ru/post/1235419/


All Articles