【问题标题】:Open cmd prompt for user input with node使用节点打开 cmd 提示以供用户输入
【发布时间】:2021-06-22 15:22:09
【问题描述】:

我创建了一个节点脚本,它应该作为后台进程运行。在脚本开始运行运行后,我需要获取一些用户数据(用户名和密码)。

获取用户数据后,我希望关闭终端,但该进程应继续在后台运行。

更复杂的是,节点脚本是使用 pkg lib 构建的,并将作为 .exe 启动

pkg on NPM

下面是将要执行的代码:

async function init() {
  try {
    await fetchConfig();
    const credentials = await getCredentials(); // this one prompts the request for user input
    watchForNewFiles(credentials); // that one should use the credentials and continue running in the background.
  } catch (e) {
    console.error(e);
  }
}

init();

【问题讨论】:

  • 请显示代码... :)
  • @NelsonTeixeira 更新

标签: javascript node.js terminal


【解决方案1】:

AFAIU 这在 node.js 的运行代码内部是不可能做到的。

您必须使用某种工具将 node.js 程序置于后台。

This answer 列出了几个用于此目的的工具。

This one 也很有用。

【讨论】:

    【解决方案2】:

    这里有一个解决方案:

    // Neccesary libs
    let fs = require("fs");
    let child_process = require("child_process");
    
    // Filename should end in .bat
    let filename = "__tmp.bat";
    
    // Main function, call this to prompt the values.
    function prompt() {
    // Write batch script
    // Prompts 2 variables & writes them as JSON into the same file
    fs.writeFileSync(filename,`@echo off
    set /p Var1="Name: "
    set /p Var2="Password: "
    echo {"name": "%Var1%", "password": "%Var2%"} > ${filename}
    exit`);
    
    // Execute the script in a cmd.exe window & write the result into stdout & parse it as JSON
    let result = JSON.parse(child_process.execSync(`start /w cmd /c ${filename} && type ${filename}`));
    
    // Delete the file
    fs.unlinkSync(filename);
    return results;
    }
    
    // Example usage:
    console.log(prompt()) // prints { name: 'hi', password: 'world' }
    

    作为 node14-win-x64 pkg 二进制文件测试,完美运行。

    【讨论】:

    • 你能解释一下这里发生了什么吗?
    • 我们编写了一个批处理文件,该批处理文件要求您提供一些变量。 (set /p) 当批处理文件被执行时,这些变量被写入同一个文件。 (echo ... %Var1% ... > ${filename})。然后我们在 cmd.exe 窗口中启动批处理文件 (child_process.execSync('start /w cmd /c ${filename}) 并读取批处理文件写入的内容 (type ${filename}) 并将其解析为 JSON (JSON.parse)。然后我们删除文件(其中包含不再需要的输出,fs.unlinkSync(filename))。我们需要这样做,因为 CMD.exe 本身并不这样做。
    • 但目前原脚本正在提示用户输入的请求
    • 这不是它应该做的吗?我错过了什么吗?
    • 当前脚本要求用户输入用户名和密码。然后在保持终端窗口打开的同时运行。我想保持相同的行为,但不是保持终端窗口打开,而是关闭它但保持进程在后台运行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    相关资源
    最近更新 更多