thedev
thedev

Reputation: 2906

Node.js conditional require

Consider plugin c is supported in recent versions of Node. What would be the best way to conditionally load it?

module.exports = {
  plugins: [   
    require("a"),
    require("b"),
    [require("c"), { default: false }] //only if node version > 0.11
  ]
};

Upvotes: 6

Views: 8407

Answers (4)

michelem
michelem

Reputation: 14590

You could use process.version:

var subver = parseFloat(process.version.replace(/v/, ''));

module.exports = {
  plugins: [   
    require("a"),
    require("b"),
    (subver > 0.11) [require("c"), { default: false }]
  ]
};

Upvotes: 0

bigblind
bigblind

Reputation: 12867

Make sure you add the semver package as a dependenc, then:

var semver = require("semver")
var plugins = [   
    require("a"),
    require("b"),
  ];

if(semver.gt(process.version, "0.11")){
    plugins.push(require("c"));
}

module.exports = {
  plugins: plugins
};

This code checks for the node version using process.version, and appends the required plugin to the list if it is supported.

Upvotes: 4

Ryan
Ryan

Reputation: 14649

If you want to make sure the major part of the version number is 0 and the minor part of the version number is greater than 11 you could use this

var sem_ver = process.version.replace(/[^0-9\.]/g, '').split('.');

if(parseInt(sem_ver[0], 10) == 0 && parseInt(sem_ver[1], 10) > 11)) {
    // load it

}

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22405

What you want to do is check the process object. According to the documentation, it will give you an object like so:

console.log(process.versions);

{ http_parser: '1.0',
  node: '0.10.4',
  v8: '3.14.5.8',
  ares: '1.9.0-DEV',
  uv: '0.10.3',
  zlib: '1.2.3',
  modules: '11',
  openssl: '1.0.1e' }

Then, simply process out the node property into a conditional if in your object.

Upvotes: 0

Related Questions