Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - How to get the version of a dependency

Is there a way to get the version of an external dependency in JS code, without hardcoding it?

like image 243
Divyansh Goenka Avatar asked Sep 16 '25 03:09

Divyansh Goenka


1 Answers

If you wanted to get the value of express you could do something like the following. You are looping over each folder in the node modules and adding the name and the version to an object.

const fs = require('fs');

const dirs = fs.readdirSync('node_modules');
const packages = {};

dirs.forEach(function(dir) {
   const file = 'node_modules/' + dir + '/package.json';
   const json = require(file);
   const name = json.name;
   const version = json.version;
   packages[name] = name;
   packages[version] = version;
});

console.log(packages['react-native']); // will log the version
like image 104
Paul Fitzgerald Avatar answered Sep 17 '25 17:09

Paul Fitzgerald