Install programmatically a NPM package providing its version

Viewed 22555

I found how to install npm packages programmatically and the code works fine:

var npm = require("npm");
npm.load({
    loaded: false
}, function (err) {
  // catch errors
  npm.commands.install(["my", "packages", "to", "install"], function (er, data) {
    // log the error or data
  });
  npm.on("log", function (message) {
    // log the progress of the installation
    console.log(message);
  });
});

If I want to install the first version of hello-world package, how can I do this in the NodeJS side, using npm module?

I know that I can use child process, but I want to choose the npm module solution.

4 Answers

I'm the author of module that allow to do what you have in mind. See live-plugin-manager.

You can install and run virtually any package from NPM, Github or from a folder.

Here an example:

import {PluginManager} from "live-plugin-manager";

const manager = new PluginManager();

async function run() {
  await manager.install("moment");

  const moment = manager.require("moment");
  console.log(moment().format());

  await manager.uninstall("moment");
}

run();

In the above code I install moment package at runtime, load and execute it. At the end I uninstall it.

Internally I don't run npm cli but actually download packages and run inside a node VM sandbox.

To install a specific version just use:

  await manager.install("moment", "2.20.1");
Related