将node.js模块中的函数readline集成到read_line函数中,以获取用户input

//normal nodejs module readline const readline = require('readline'); //I want to integrate readline module into my function read_line so as to I can get user input by use read_line ,but my mind is wrong. //I know the reason is that js function will not be blocked by Function,but I am not familiar with nodejs,how can it block subsequent code run? function read_line() { var input; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.on('line', function (input) { this.input = input; rl.close(); }); return input; } //it will run right now,return undefined var s = read_line(); //i want to console the user input console.log(s); 

我想集成readline模块到我的函数read_line中,以便我可以通过使用read_line获得用户input,我需要帮助!

readline是asynchronousfunction

 rl.on('line', function (input) { this.input = input; rl.close(); }); 

该函数将等待“ ”事件被触发

当你调用函数read_line()会运行同步并返回input;

你可以使用一个callback函数,所以当' line '事件被触发时,callback函数将被调用

 const readline = require('readline'); function read_line(cb) { const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.on('line', function (input) { cb(input) rl.close(); }); } read_line(function(input){ console.log(input); });