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.
source share