首页 > 解决方案 > 通过前端安装 NPM 模块

问题描述

我正在开发一个应用程序,我希望能够通过前端安装 NPM 模块。不过,我不知道该怎么做。也就是说,我知道如何通过前端进行 CRUD 操作,但我不知道如何与命令行交互或通过前端运行命令行功能。

有没有可以帮助解决这个问题的包,或者它是否以某种方式内置于 Node.js 中?

简而言之,如何以可以安装 NPM 包的方式将前端连接到后端?

标签: node.jsnpmnpm-installnpm-scripts

解决方案


你想要的是child_process模块。它是内置的,因此您无需安装任何额外的模块。

大多数情况下,您要查找的是spawn()or 或exec()

例如,如果您想运行npm install some_module,您可以执行以下操作:

const { exec } = require('child_process');

let command = 'npm install some_module';
let options = { cwd: '/path/to/node/project' };

exec(command, options, (error, stdout, stderr) => {
    // Do anything you want with program output here:
    console.log('output:', stdout, stderr);
});

推荐阅读