Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I require a minimum version of node.js in my script?

Tags:

node.js

I just found out that a script I wrote only works on node 0.10 because it uses readable events.

How do I require a minimum version of node.js in my script so that users know that they need to upgrade?

like image 454
hwiechers Avatar asked Sep 11 '13 08:09

hwiechers


People also ask

How do I specify node version?

The n command for installing and activating a version of Node is simple: n 6.17. 1 . You could also use n latest for the latest version of Node or n lts for the latest LTS version of Node. If the version of Node is already installed, then n will simply switch to that version.

Can I specify node version in package json?

Use the engines keyword in the package. json file to specify the Node. js version that you want your application to use. You can also specify a version range using npm notation.


2 Answers

In package.json:

{ "engines" : { "node" : ">=0.10.3" } }

From the docs.

Edit, a programmatic way:

var pkg = require('./pacakge'),
    semver = require('semver');

if(!semver.satisfies(process.version, pkg.engines.node)) {
  // Not sure if throw or process.exit is best.
  throw new Error('Requires a node version matching ' + pkg.engines.node);
}
like image 131
Andreas Hultgren Avatar answered Nov 15 '22 07:11

Andreas Hultgren


Add this to top the top of your script.

var versionComps = process.versions['node'].split('.');
if (parseInt(versionComps[0]) === 0 && parseInt(versionComps[1]) < 10) {
  console.log('Script requires node.js version >= 0.10');
  process.exit(1);
};
like image 45
hwiechers Avatar answered Nov 15 '22 08:11

hwiechers