The below node JS program order of execution is totally different, can anyone explain to me how the execution is happening?
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
function getname()
{
let name=""
readline.question('Who are you?', name =>
{
console.log(`Hey there ${name}!`);
readline.close();
});
return name
}`enter code here`
console.log('My name is' getname())
output : Who are you?My name is Summer Hey there Summer!
I only got to understand that this code doesn't work in sequence order as Node JS is asynchronous programming language.
CodePudding user response:
The answer has 2 parts
- How
readline.question
library works - Evaluation of a statement
The rl.question() method displays the query by writing it to the output, waits for user input to be provided on input, then invokes the callback function passing the provided input as the first argument.
So in the above example, for Node to print out value of 'My name is' getname()
, it has to evaluate this expression.
The evaluation returns nothing as name is empty. But as readline.question
gets executed, it prints out Who are you ?
as the question
method displays the query by writing it to output
As the evaluation of 'My name is' getname()
is complete, it prints My name is
and waits for the prompt to input. Lets say thats gp
Once thats done, it would print the input gp
(obviously as we typed it) followed by the callback output i.e Hey there gp!
Hope this makes sense
CodePudding user response:
Order of operations:
- You are executing the function inside the console.log first (
getname()
) getname()
is causing the stdin prompt to display "Who are you?"- It is executing synchonously so it displays the question
- Synchronously, the input is received from the stdin (you type it at the prompt) which then evaluates the
console.log('My name is' getname())
expression. - the
getname()
logic now finished, then outputs 'Hey there Summer!' on the console.
The documentation may help here as well:
import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
const rl = readline.createInterface({ input, output });
const answer = await rl.question('What do you think of Node.js? ');
console.log(`Thank you for your valuable feedback: ${answer}`);
rl.close();