等待用户在 Node.js 中输入 [英] Waiting for user to enter input in Node.js

查看:136
本文介绍了等待用户在 Node.js 中输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解 Node.js 中异步事件的基本原理,并且我正在学习如何以这种方式编写代码.但是,我遇到了以下情况:

I understand the rationale in Node.js for asynchronous events and I am learning how to write code that way. However, I am stuck with the following situation:

我想编写偶尔为用户输入暂停的代码.

I want to write code that occasionally pauses for user input.

该程序不是用作服务器(尽管目前它是用于命令行的).我意识到这是 Node.js 的一种非典型用法.我的目标是最终将程序迁移回客户端 Javascript 应用程序,但我发现在 Node.js 中工作既有趣又对调试非常有用.这让我回到了说明问题的示例:

The program is not intended as a server (though currently it's intended for the command line). I realize this is an atypical use of Node. My goal is to eventually migrate the program back to a client-side Javascript application, but I find working in Node.js to be both fascinating and very useful for debugging. This brings me back to my example that illustrates the problem:

它读入一个文本文件并输出每一行,除非该行以?"结尾.在这种情况下,它应该暂停让用户澄清该行的含义.目前我的程序首先输出所有行,然后等待最后的澄清.

It reads in a text file and outputs each line unless the line ends with a "?". In that case, it should pause for user to clarify what was meant by that line. Currently my program outputs all lines first and waits for the clarifications at the end.

是否有任何方法可以强制 node.js 在条件触发的情况下(即行以?"结尾)精确地暂停命令行输入?

Is there any way to force node.js to pause for command-line input precisely for the cases where the conditional fires (i.e., where the line ends with a "?")?

var fs = require("fs");
var filename = "";
var i = 0;
var lines = [];

// modeled on http://st-on-it.blogspot.com/2011/05/how-to-read-user-input-with-nodejs.html
var query = function(text, callback) {
    process.stdin.resume();
    process.stdout.write("Please clarify what was meant by: " + text);
    process.stdin.once("data", function(data) {
        callback(data.toString().trim());
    });
};

if (process.argv.length > 2) {
    filename = process.argv[2];
    fs.readFile(filename, "ascii", function(err, data) {
        if (err) {
            console.error("" + err);
            process.exit(1);
        }
        lines = data.split("\n");
        for (i = 0; i < lines.length; i++) {
            if (/\?$/.test(lines[i])) { // ask user for clarification
                query(lines[i], function(response) {
                    console.log(response);
                    process.stdin.pause();
                });
            }
            else {
                console.log(lines[i]);
            }
        }
    });
}
else {
    console.error("File name must be supplied on command line.");
    process.exit(1);
}  

推荐答案

这是另一种没有依赖关系的方法 (readline 是内置的)

Here's another way that has no dependencies (readline is built-in)

const readline = require('readline');

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

    return new Promise(resolve => rl.question(query, ans => {
        rl.close();
        resolve(ans);
    }))
}


const ans = await askQuestion("Are you sure you want to deploy to PRODUCTION? ");

这篇关于等待用户在 Node.js 中输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆