Open cmd prompt for user input with node

Viewed 274

I have created a node script which should run as a background process. Right after the script starts running run I need to get some user data (username & password).

After getting the user data I wish to close the terminal but the process should continue running in the background.

To complicate things, the node script is being built with pkg lib and will be started as an .exe

pkg on NPM

Here is a the code that will be executed:

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();

2 Answers

Here's a solution:

// 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' }

Tested as a node14-win-x64 pkg binary, works perfectly.

AFAIU this is not possible to do from inside node.js's running code by itself.

You have to use some kind of tool to put the node.js program in the background.

This answer lists several tools for this purpose.

This one is also useful.

Related