Can I install a NPM package from a javascript file running in Node.js? For example, I'd like to have a script, let's call it "script.js" that somehow (...using NPM or not...) install a package usually available through NPM. In this example, I'd like to install "FFI". (npm install ffi)
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fs
- Keeping track of variable instances
it can actually be a bit easy
I had a heck of a time trying to get the first example to work inside a project directory, posting here in case anyone else finds this. As far as I can tell, NPM still works fine loaded directly, but because it assumes CLI, we have to repeat ourselves a little setting it up:
I'm the author of a module that allow to do exactly 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:
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.yes. you can use child_process to execute a system command
if you want to have output as well you can use:
this way you can watch the installation like you do it on hand and avoid bad surprises (buffer full, etc)
pacote is the package that npm uses to fetch package metadata and tarballs. It has a stable, public API.