Checking Node Version on Runtime

April 21, 2019

I was building an app with Node version 10, which used some “new” features that didn’t exist in Node.js v8. This makes me wonder if there’s a way to check the version of Node installed on the system on runtime, so instead of scary callstack traces, I can display an nice and user friendly error message giving the user a hint their Node installation is not up-to-date, if he or she is not careful enough to read through all the system requirements in the docs.

And here’s just a simple way to do this by checking process.version:

> process.version
'v10.15.3'

To make better use of this information, we can use the semver module to test process.version against the versions or version range we have in mind in regard of Semantic Versioning Specification. Let’s say we want to exit the program when the user has a Node version below v10, but also higher than v11.

const semver = require('semver');

if (!semver.satisfies(process.version, '10 - 11')) {
  console.error('Please use Node.js v10 or v11 to run this script!');
  process.exit(1);
}

// other code...

Fast and easy. :D