S
S
Svyatoslav Khusamov2019-10-04 17:23:13
Node.js
Svyatoslav Khusamov, 2019-10-04 17:23:13

How to download (require) a package that is not installed?

Let's say there is package1 in the NPM registry.
His name will be known only during the execution or installation of my script.
For example, when installing my script, its config will contain a list of packages that need access (their APIs are the same, for example, all packages export getFunctions).
From my script, I want to access it without setting:

const packageName = 'package1'; // Имя пакета заранее не известно.
const pkg = require(packageName);
const pkgFunctionList = pkg.getFunctions();

Is it possible to access a package without installing the 'npm install' view?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Michael, 2019-10-04
@notiv-nt

Something like this

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

try {
  require('nnn');
} catch (e) {
  if (e.code === 'MODULE_NOT_FOUND') {
    exec('npm i nnn', (err, stdout) => {
      if (err) {
        console.error(err);
      }

      console.log(stdout);
    });
  }
}

or install them in postinstall ?

S
Svyatoslav Khusamov, 2019-10-04
@khusamov

Theoretically, you can install via exec the package globally and import using https://github.com/sindresorhus/import-global

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question