Open In App

How to define the required Node.js version in package.json?

Last Updated : 05 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

To define the required Node.js version in the package.json file we will have to go through few simple steps:

Step 1: Our first and foremost step should be to choose a project on which we are going to work, for example, I will be choosing a simple JavaScript project. In the project, we will be having a package.json file, if not we will have to create a package.json file in the same directory. 

Step 2: After creating our Package.json file we will make use of the engines field to specify the version of Node.js that the project requires in order to run, therefore we will add few lines in our Package.json file following the same syntax to specify the required Node.js version for the project:

Syntax:

 “engines”: {

   “node”: “> or < =version_number”,

   “npm”: “> or < =version_number”

 },

Output:

Image depicting the correct syntax

Here in the above output image, we can see that we have defined our required node version to be greater than or equal to 15.0.0 and npm version to be less than or equal to 5.0.0, therefore when we try to run any operation using node then first it will check if the required version matches with the present version or not and if not it displays errors.

Step 3: In order to display errors in the command prompt or terminal when there is a mismatch in the node.js version, we will have to create a .npmrc file in the same directory in which the package.json is present.

What is the .npmrc file? 

In simple terms .npmrc file can be defined as a file that is a configuration file for NPM, and it defines the settings on how NPM should behave when running commands.

Now create a .npmrc file and add the following code engine-strict=true in it, because of which it will force display errors if there is a mismatch in the versions of node and npm.

Actual required syntax of the .npmrc file

Step 4: Now, our final step should be to test if we are getting errors or not while there is a Node.js and npm version mismatch, and to test it I will be using a simple command npm install and we get the following errors. 

Output:

Error showing the node and npm version mismatch

Reference:

How to create a Package.json file: https://www.geeksforgeeks.org/node-js-package-json/


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads