When interacting with clis, for example, taking npm init, we can run the command and get the output by the following code
const { exec } = require('child_process');
exec('npm init', (err, stdout, stderr) => {
if (err) {
console.error(err)
} else {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
}
});
But we cannot pass the project name, version name etc.. How to achieve this. Pls answer with the example of npm init command
Thanks in advance :)
Use the stdin channel each process provides. For that, use the node child_process.spawn method instead:
const { spawn } = require('child_process');
const npm = spawn('npm', ["init"]);
npm.stdout.pipe(process.stdout);
npm.stderr.pipe(process.stderr);
npm.on("exit", () => {
console.log("npm exited");
process.exit();
});
const answers = [
"my-awesome-cli", // package name
"0.0.1", // version number
"desciprtion", // description
"index.js", // entry point
"", // test command
"", // git reposiroty
"", // keywords
"Marc Stirner", // author
"MIT" // license
];
setInterval(() => {
if (answers.length > 0) {
// get first item from array
let answer = answers.shift();
// print value we pass to npm
console.log("Write to npm child:", answer);
// write chunk to stdin
npm.stdin.write(`${answer}\r\n`);
} else {
//npm.stdin.end();
console.log("Hit final enter")
npm.stdin.write(`\r\n`);
}
}, 800);
My example spwans the npm command, use the stdin channel to write the answer to the process, and pipe the stdout&stderr output from the npm command to the node.js process.
You can do this with exec too, since it returns as well a child_process object.
Read more on the node.js docs, they are very well documented.