Before npm 8.0 was possible to install npm packages programmatically, like this:
const npm = require('npm');
npm.load((error) => {
if (error) return console.log(error);
npm.commands.install([package], (error, data) => {
if (error) return console.log(error);
// command succeeded, and data might have some info
});
npm.on('log', (message) => {
console.log(message);
});
});
But they decided to refactor things and the support for programmatic API was dropped. Of course, there is the option to keep npm version bellow 7.24.2 which is the last supporting version, but some vulnerabilities were found in those versions and despite the fact that they are harmless in my case the console looks scarry for users.
Is there any reliable alternative to this issue?
Solved by using child_process.:
const { exec } = require('child_process');
const run = async (cmd) => {
const child = exec(cmd, (err) => {
if (err) console.error(err);
});
child.stderr.pipe(process.stderr);
child.stdout.pipe(process.stdout);
await new Promise((resolve) => child.on('close', resolve));
};
module.exports = run;
then... in another file in some function we can call:
await run(`npm install ${package}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With