Sogrey / Web-QA

https://sogrey.github.io/Web-QA/
MIT License
6 stars 2 forks source link

Node.js 如何接收用户输入 #208

Open Sogrey opened 4 years ago

Sogrey commented 4 years ago

Readline

// 引入readline模块
var readline = require('readline');

//创建readline接口实例
var  rl = readline.createInterface({
    input:process.stdin,
    output:process.stdout
});

// question方法
rl.question("你叫什么?",function(answer){
    console.log("名字是:"+answer);
    // 不加close,则不会结束
    rl.close();
});

// close事件监听
rl.on("close", function(){
   // 结束程序
    process.exit(0);
});

输入与输出

// 引入readline模块
var readline = require('readline');

var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.on('line', function(line){
    switch(line.trim()) {
        case 'copy':
            console.log("复制");
            break;
        case 'hello':
            rl.write("Write");
            console.log('world!');
            break;
        case 'close':
            rl.close();
            break;
        default:
            console.log('没有找到命令!');
            break;
    }
});
rl.on('close', function() {
    console.log('bye bye');
    process.exit(0);
});

类似命令行的输入输出

var readline = require('readline');
var  rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('Test> ');
rl.prompt();

rl.on('line', function(line) {
    switch(line.trim()) {
        case 'copy':
            console.log("复制");
            break;
        case 'hello':
            console.log('world!');
            break;
        case 'close':
            rl.close();
            break;
        default:
            console.log('没有找到命令!');
            break;
    }
    rl.prompt();
});

rl.on('close', function() {
    console.log('bye bye!');
    process.exit(0);
});

https://blog.csdn.net/zgljl2012/article/details/48321171