如何从Node.js中的控制台读取数据?

时间:2018-01-06 09:27:50

标签: node.js

其实我试过一个代码。这段代码工作正常,但我想在回调函数之外访问这些信息。但我无法找到解决方案。

var prompt = require('prompt');

  prompt.start();

  prompt.get(['username', 'email'], function (err, result) {

    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);

    data = result.username;
  });

console.log(data);

如果我试图检索打印数据变量,则会显示错误。

Admins-MacBook-Pro:Basic node programs Sandeep$ node Node3.js 
prompt: username:  /Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22
console.log(data);
            ^

ReferenceError: data is not defined
    at Object.<anonymous> (/Users/Sandeep/Desktop/NodeJS/Node example/Basic node programs/Node3.js:22:13)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

2 个答案:

答案 0 :(得分:1)

&#34;您无法在回调函数之外访问该变量。原因是,Node.js具有一个特殊功能,即将回调函数作为执行异步IO任务后要执行的下一个代码块传递。&#34;

请参阅此文章:how can find return variable value outside anonymous function in node js mysql query function

您还可以查看此链接,了解如何处理异步流:http://book.mixu.net/node/ch7.html

答案 1 :(得分:1)

您可以使用承诺,检查有关承诺的文档以及更新的es 6 Async / await。有希望你可以使用这样的东西:

var prompt = require('prompt');

function getPromt () {  return new Promise( (resolve, recect) => {
   prompt.start();

   prompt.get(['username', 'email'], function (err, result) {
    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);
    resolve( result.username);
    });
  });
}
getPromt().then(data =>
console.log('After promise ' + data), ()=>{});