'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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1