Skip to content

Instantly share code, notes, and snippets.

@Kepro
Created September 23, 2022 10:31
Show Gist options
  • Save Kepro/74e7db82cc7ca07c64bfe4f705f8bfb3 to your computer and use it in GitHub Desktop.
Save Kepro/74e7db82cc7ca07c64bfe4f705f8bfb3 to your computer and use it in GitHub Desktop.
Check installed version of node.js before running npm start or npm install
// in package.json
/*
{
"engines": {
"node": ">=16",
"npm": ">=7"
},
"scripts": {
"preinstall": "node checkNodeVersion",
"prestart": "node checkNodeVersion",
...
}
}
*/
const pjson = require('./package.json');
const WANTED_VERSION = pjson.engines.node.match(/[0-9].*/)[0]; // or use your number
const result = process.versions;
if (result && result.node) {
if (parseInt(result.node) >= WANTED_VERSION) {
console.log(`✨ Node Version: ${result.node}`);
} else {
console.log(`✋ Package installation(npm install) or Project startup command(npm start) failed due to Node Version.`);
console.log(`Please install and use Node Version >=${WANTED_VERSION}`);
console.log(`Your current Node Version is: ${result.node}`);
console.log(`
To install Node v${WANTED_VERSION} run:
nvm install v${WANTED_VERSION}
nvm use v${WANTED_VERSION}
`);
process.exit(1);
}
} else {
console.log('Something went wrong while checking Node version');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment