How to Read Package Version in node.js Code?

Better Stack Team
Updated on April 4, 2024

To read the package version in Node.js code, you can use the require function to import the package.json file and access the version property. Here's an example:

Assuming your project structure looks like this:

 
project-root
│   package.json
│   yourScript.js
  1. Modify your package.json file to include a version field:

     
    {
      "name": "your-project",
      "version": "1.0.0",
      "description": "Your project description",
      // other fields...
    }
    
  2. In your Node.js script (yourScript.js), read the package version:

     
    const packageInfo = require('./package.json');
    
    // Access the version property
    const version = packageInfo.version;
    
    console.log('Package version:', version);
    

    Make sure to adjust the path in the require statement if your script is in a different location relative to the package.json file.

Alternatively, you can use the fs (file system) module to read the contents of the package.json file and then parse the JSON data to retrieve the version:

 
const fs = require('fs');

// Read the content of package.json
const packageJsonContent = fs.readFileSync('./package.json', 'utf8');

// Parse the JSON data
const packageInfo = JSON.parse(packageJsonContent);

// Access the version property
const version = packageInfo.version;

console.log('Package version:', version);

Using require is a more convenient and common approach, but reading the file manually gives you more flexibility in case you need to perform additional operations on the package.json data.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github