Nodejs - How to get the version of a dependency

Viewed 1824

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

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
Related