I need to programmatically access the current node version running in a library I am writing. Can\'t seem to find this in the docs.
I had the similar issue with my codebase. I wanted to know the current NodeJs version I am going to use to run my server at runtime. For that, I wrote a code which can be run before starting the Server using npm run start script.
Found below code helpful from this question.
'use strict';
const semver = require('semver');
const engines = require('./package').engines;
const nodeVersion = engines.node;
// Compare installed NodeJs version with required NodeJs version.
if (!semver.satisfies(process.version, nodeVersion)) {
console.log(`NodeJS Version Check: Required node version ${nodeVersion} NOT SATISFIED with current version ${process.version}.`);
process.exit(1);
} else {
console.log(`NodeJS Version Check: Required node version ${nodeVersion} SATISFIED with current version ${process.version}.`);
}
My package.json looks like this:
{
"name": "echo-server",
"version": "1.0.0",
"engines": {
"node": "8.5.0",
"npm": "5.3.0"
},
"description": "",
"main": "index.js",
"scripts": {
"check-version" : "node checkVersion.js",
"start-server" : "node app.js"
"start" : "npm run check-version && npm run start-server",
"test": "npm run check-version && echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"bluebird": "^3.5.1",
"express": "^4.16.3",
"good-guy-http": "^1.10.3",
"semver": "^5.5.0"
}
}
Do run npm install command before you run npm run start command to run your project.