Answer the question
In order to leave comments, you need to log in
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();
Answer the question
In order to leave comments, you need to log in
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);
});
}
}
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 questionAsk a Question
731 491 924 answers to any question