Skip to content

Instantly share code, notes, and snippets.

@hputzek
Last active May 20, 2021 10:20
Show Gist options
  • Save hputzek/03d642eb4a710adc997184526da1546b to your computer and use it in GitHub Desktop.
Save hputzek/03d642eb4a710adc997184526da1546b to your computer and use it in GitHub Desktop.
Check major node version before npm install
/**
* This script must execute before "npm install"
* Lock the major version of Node running based on the one set in the package.json
* Works by setting a major version in package.json (e.g. "14" or "15"....) in the "engines.node" section.
*/
const path = require("path");
const packageJson = require(path.join(process.cwd(), "package.json"));
const requiredNodeVersion = parseInt(packageJson.engines.node);
const runningNodeVersion = process.version;
const runningMajorNodeVersion = parseInt(
runningNodeVersion
// only look for major version
.split(".")[0]
// remove the 'v' at the beginning of version string
.substring(1)
);
// check that the required version of Node is running
if (runningMajorNodeVersion >= requiredNodeVersion) {
console.info(
`Node version check successful. You're running node ${runningNodeVersion}`
);
} else {
console.error(
`You are not running the required version of Node. Please use node >= v${requiredNodeVersion}.`
);
// kill the process if the required node version is not the one running
process.exit(1);
}
{
"preinstall": "node scripts/path...to.../nodeVersionCheck.js"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment