我创建了一个应该作为后台进程运行的 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/