检测按键并在控制台中替换线路

时间:2016-05-18 01:05:51

标签: node.js

我有一个Node.js脚本,如下所示:

var chalk = require("chalk");
var https = require("https");
var express = require("express");
var fs = require("fs")
var app = express();
const readline = require("readline");
var keypress = require("keypress");
var process = require("process");
var emitter = require("emitter");

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

console.log('       _______');
console.log('      /     o \\    .------------------------.');
console.log('     |         >   |   Welcome to chikin!   |');
console.log('      \\_______/    |  A npm package manager |');
console.log("        |   |      '------------------------'");
console.log('        ^   ^');
console.log('_____________________________________________\n');
console.log(chalk.bold.green('What would you like to do?') + ' Type ' + chalk.bold.blue('a') + ',' + chalk.bold.blue('b') +  ', or ' +  chalk.bold.blue('c'));
console.log('_________________________________________');
console.log('a. ' + chalk.bold.blue('Install Packages'));
console.log('b. ' + chalk.bold.blue('Update Packages'));
console.log('c. ' + chalk.bold.blue('Uninstall Packages\n'));

var du = '';
var valid = false;

rl.question('?> ', function(answer) {
    var areValid = ['a', 'b', 'c', 'A', 'B', 'C', 'a.', 'b.', 'c.', 'A.', 'B.', 'C.'];
    if (answer in areValid) {
        valid = true;
    }
})

此脚本正在尝试检测用户是否想要A. 安装软件包,B。更新软件包或C. 卸载软件包 。使用rl.question()方法并不起作用,因为当我运行它时,光标只是闪烁,并且不允许我键入任何内容。所以,我没有使用提示,而是想我可以通过按键检测它。虽然我不知道该怎么做。我也在想它可以用最新的有效答案替换控制台的最后一行。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

第三方模块如何处理?与thisthat

相同

答案 1 :(得分:1)

使用readline时,您应始终锁定用户输入状态(paused

我希望这会有所帮助,祝你好运:

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

const LINE = '';
const LINE2 = '\n';

const PROMPT = '?> ';

rl.setPrompt(PROMPT);

// prevent user input by default: lock the state
rl.pause();

var steps = {

    a: function()
    {
        console.log('You selected "Install Packages"', LINE);

        var trials = 0;
        ask('Enter package name(s) (separated with , ) you want to install:', function(answer)
        {
            var packages = answer.toLowerCase().split(/[^a-z_\-]/).filter(function(pkg) {
                return pkg.length;
            });

            if (!packages.length)
            {
                if (++trials > 2)
                {
                    console.log('Are you kidding me?');
                    process.exit();
                }

                return false; // ask again
            }

            confirm('Packages below will be installed, are you confirm? ( y/Y or not )' 
                + LINE2 + ' --> ' + packages.join(', '), function(answer)
                {
                    console.log(LINE2);

                    if (!answer)
                    {
                        steps.a(); // start this step again
                        return;
                    }

                    console.log('You confirmed but', LINE);
                    steps.c(1);
                });
        });
    },

    b: function()
    {
        console.log('You selected "Update Packages"', LINE);
        console.log('Now, please enter the package name you want to update: ');

        input('acme-package', function(pkg) {

            if ('acme-package' !== pkg)
            {
                console.log('Really!?', LINE);
                process.exit();
            }
            // else
                steps.c(1);
        });
    },

    c: function(internal)
    {
        if (!internal) {
            console.log('You selected "Uninstall Packages"', LINE);
        }

        console.log("Sorry, I don't know what to do now.", LINE, 'Program will exit.');
        process.exit();
    }
};

/**
 * Test
 */
console.log('What would you like to do?', LINE2);

console.log('a. Install Packages', LINE);
console.log('b. Update Packages', LINE);
console.log('c. Uninstall Packages', LINE2);

ask('What would you like to do?', function(answer) {

    answer = answer.toLowerCase();

    if (!steps[answer]) {
        return false;
    }

    steps[answer]();
    // first step: after this point you can handle other events in your 'steps'
});


/**
 * Functions
 */
function confirm(message, callback)
{
    console.log(message, LINE);
    // print confirmation message

    rl.pause();
    // lock: ensure

    rl.question(PROMPT, function(answer)
    // unlock
    {
        rl.pause();
        // lock again

        answer = answer.trim().toLowerCase();

        if (!answer.length) {
            confirm(message, callback); // again
        }
        else {
            callback(/^y(e(s|p|ah?))?$/.test(answer)); // y|yes|yep|yea|yeah
        }
    });
}

function ask(question, placeholder, callback)
{
    if (typeof placeholder === 'function')
    {
        callback = placeholder;
        placeholder = null;
    }

    console.log(question, LINE);
    // print question message

    rl.pause();
    // lock

    rl.question(PROMPT, function(answer)
    // unlock
    {
        rl.pause();
        // lock again

        var response = callback(answer.trim());
        if (response) {
            ask(typeof response === 'string' ? response : question, placeholder, callback);
            // again
        }
    });

    if (placeholder) {
        rl.write(placeholder);
    }
}

function input(placeholder, callback)
{
    if (typeof placeholder === 'function')
    {
        callback = placeholder;
        placeholder = null;
    }

    rl.pause();
    // lock

    rl.question(LINE + PROMPT, function(answer)
    // unlock
    {
        rl.pause();
        // lock again

        var answer = answer.trim();

        if (!answer || callback(answer) === false) {
            input(callback);
        }
    });

    if (placeholder) {
        rl.write(placeholder);
    }
}

process.on('exit', function()
{
    rl.pause();
    // always lock before 'console.log'

    console.log(LINE, 'bye!');
});

奖金:

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

var pr = '+';

setInterval(function() {

    rl.setPrompt(pr += '+');

    rl.prompt();
    rl.pause();

    if (pr.length > 20) {
        process.exit();
    }

}, 100);