javascript - 使用 Node 打开用户输入的 cmd 提示

标签 javascript node.js terminal

我创建了一个应该作为后台进程运行的 Node 脚本。在脚本开始运行之后,我需要获取一些用户数据(用户名和密码)。
获取用户数据后,我希望关闭终端,但该进程应继续在后台运行。
更复杂的是, Node 脚本是用 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);
  }
}
在里面();

最佳答案

这是一个解决方案:

// 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 二进制文件,完美运行。

关于javascript - 使用 Node 打开用户输入的 cmd 提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66806063/

相关文章:

javascript - thymeleaf - 脚本和 :block

javascript - .load() 后回调函数不执行点击

node.js - Node 模块化架构

macos - 如何使箭头键在MIT Scheme解释器中起作用?

Javascript 表单验证(多个条件)

JavaScript 命名空间模式(类似于对象的属性)

javascript - 将评估结果保存到变量中- Nightmare 网抓取

javascript - 有没有办法为 Node.js (npm) 应用程序创建快捷方式桌面?

在 Mac 终端中编译并运行 Sublime Text 文件

python - shutil.get_terminal_size() 不变