5

I have a service where I want to allow users at install-time to specify which persistence engine to use, i.e. file-based, MongoDB, or Redis, and I'm looking for some npm magic where you only download the necessary modules (none, mongodb, or redis, respectively).

Is this possible? I can't find any options other than defining dependencies and devDependencies in package.json, and that's not appropriate for this.

Note also that while the mongodb and redis modules may be relatively small, consider an alternate case where you may optionally need Java for RMI communication.

Thanks!

anthonyserious
  • 1,030
  • 10
  • 14
  • There is an [`optionalDependencies` field](https://docs.npmjs.com/files/package.json#optionaldependencies), but that's not what you're looking for. – Scimonster Dec 31 '14 at 19:04
  • Actually I think that will suffice. If an optional mongodb fails to install because there's no C++ compiler or an optional node-jmx fails because there's no JRE, then that's fine. Also the documentation just shows JS code, but you can add `"optionalDependencies":{}` in your package.json and it works. If you edit something around this into your answer I'll mark it correct. – anthonyserious Dec 31 '14 at 19:35

1 Answers1

3

You might want to use a post-install script, and then install them then.

You can install things using the npm module programmatically.

So, you might do something like this:

var npm = require('npm'); // make sure npm is in your package.json!
npm.load({/* some object properties, if needed */}, function(err) {
    if (err) {return handleError(err)}
    if (usingMongoDB) {
        npm.commands.install(['mongodb'], function(err){
        if (err) {return handleError(err)}
        console.log('mongodb successfully installed');
    });
});

Now, i have never done something like this, so i recommend you look at the documentation for programmatic npm install, and also load.

Scimonster
  • 30,695
  • 8
  • 67
  • 84
  • Interesting. Running a post-install script can work of course, but I'm hoping for a one-line solution. I'd also feel weird about downloading packages from within an app after that app has already been deployed. – anthonyserious Dec 31 '14 at 18:20
  • I wouldn't recommend this approach as npm warns you not to use its api: [_Although npm can be used programmatically, its API is meant for use by the CLI only, and no guarantees are made regarding its fitness for any other purpose._](https://github.com/npm/npm#using-npm-programmatically) Instead you could use [this approach](http://stackoverflow.com/a/17537559/516433) – Lucas Jan 19 '16 at 21:54