2

I have a project that needs Node >= V14 and would like to prevent npm script execution if node version does not match.

Using .npmrc and engines in package.json, I can prevent npm install from running if node version does not match.

However, is there any way to prevent npm start from executing if appropriate node version is not found?

Aayush Gupta
  • 63
  • 4
  • 12

2 Answers2

3

Short answer: NPM does not provide a built-in feature to achieve this.


Solution:

However your requirement can be met by utilizing a custom node.js helper script:

  1. Save the following check-version.js script in the root of your project directory, i.e. save it at the same level where package.json resides

    check-version.js

    const MIN_VERSION = 14;
    const nodeVersion = process.version.replace(/^v/, '');
    const [ nodeMajorVersion ] = nodeVersion.split('.');
    
    if (nodeMajorVersion < MIN_VERSION) {
      console.warn(`node version ${nodeVersion} is incompatible with this module. ` +
          `Expected version >=${MIN_VERSION}`);
      process.exit(1);
    }
    
  2. In the scripts section of your package.json define your start script as follows:

    package.json

    ...
    "scripts": {
      "start": "node check-version && echo \"Running npm start\""
    },
    ....
    

    Note Replace the echo \"Running npm start\" part (above) with whatever your current start command is.


Explanation:

  • In check-version.js we obtain the Node.js version string via process.version and remove the v prefix using the replace() method.

    Note: You may prefer to use process.versions.node instead of replace to obtain the version string without the prepended v.

  • Next we obtain the Major version only from the version string and assign it to the nodeMajorVersion variable.

  • Finally in the if statement we check whether the nodeMajorVersion is less than the expected minimum node.js version (MIN_VERSION). If it is less than the expected version we warn the user and call the process.exit() method with the exit code as 1.

RobC
  • 22,977
  • 20
  • 73
  • 80
1

Depends on what your start does, but if it's your code:

if (process.versions.node.split('.')[0] < 14) process.exit(1)
Matt
  • 68,711
  • 7
  • 155
  • 158