首页 > 解决方案 > Readline操作的Node JS代码说明

问题描述

我是 Node JS 的新手,我写了下面的代码只是为了了解一些事情。

// for readline
    **const readline = require('readline');
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });
    var result = 0, num1, num2;
    rl.question('Enter the first number ', (num1) =>{
      rl.question('Enter the second number ', (num2) =>{
        rl.question('Enter the operation ', (opr) => {
          if(opr === '+'){result = +num1 + +num2; console.log(`Sum of ${num1} and ${num2} is ${result}`);}
          else {console.log('Invalid Arithmatic Operation Specified')};
          rl.close();
        });
      });
    });
    console.log(`${num1}`);
    rl.on("close", function() {
        console.log("\nBYE BYE !!!");
        process.exit(0);
    });**
    

这个简单的算术运算代码。根据此代码,最终控制台日志行 (console.log( ${num1});) 应在运行操作代码之后执行。但是,当我运行代码时,它会立即执行(请参阅下面的未定义输出)。有人可以解释为什么吗?

    D:\nodejs\test>node maths.js
    Enter the first number undefined
    1
    Enter the second number 2
    Enter the operation +
    Sum of 1 and 2 is 3
    
    BYE BYE !!!
    
    Regards,
    John

标签: node.js

解决方案


推荐阅读