简体   繁体   English

在 npm 决定放弃程序化 API 之后以编程方式安装 npm package

[英]Install npm package programmatically after npm decision to drop programmatic API

Before npm 8.0 was possible to install npm packages programmatically, like this:在 npm 8.0 之前,可以通过编程方式安装 npm 包,如下所示:

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.但他们决定重构事物,并放弃了对程序化 API 的支持。 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.当然,可以选择将 npm 版本保留在最后一个支持版本7.24.2以下,但在这些版本中发现了一些漏洞,尽管事实上它们对我来说是无害的,但控制台对用户来说看起来很可怕。

Is there any reliable alternative to this issue?这个问题有什么可靠的替代方法吗?

Solved by using child_process .:通过使用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:然后...在某个 function 中的另一个文件中,我们可以调用:

await run(`npm install ${package}`);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM