Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Install npm package programmatically after npm decision to drop programmatic API

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?

like image 751
Sorin GFS Avatar asked Mar 23 '26 08:03

Sorin GFS


1 Answers

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}`);
like image 103
Sorin GFS Avatar answered Mar 24 '26 22:03

Sorin GFS



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!