Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check package version at runtime in nodejs?

I have some of my entries in package.json defined as "*"

"dependencies": {
    "express": "4.*",
    "passport": "*",
    "body-parser": "*",
    "express-error-handler": "*"
},

I wan't to freeze those values to the current version. How can I know what version my packages are at run time? I don't mind checking one by one since I don't have many of them :)

BTW: I cannot do npm list --depth=0 because I cannot access the vm directly (PaaS restriction), just the logs.

like image 413
nacho4d Avatar asked Apr 20 '15 07:04

nacho4d


People also ask

How do I find the version of a package installed via npm?

Use npm view [package-name] version to know the specific latest version of a package available on the npm registry. Use npm list [package-name] to know the specific latest version of an installed package. Use npm install [package-name]@[version-number] to install an older version of a package.


1 Answers

You can use the fs module to read the directories in the node_modules directory and then read package.json in each of them.

var fs = require('fs');
var dirs = fs.readdirSync('node_modules');
var data = {};
dirs.forEach(function(dir) {
    try{
    var file = 'node_modules/' + dir + '/package.json';
    var json = require(file);
    var name = json.name;
    var version = json.version;
    data[name] = version;
    }catch(err){}
});
console.debug(data['express']); //= 4.11.2
like image 136
laggingreflex Avatar answered Sep 20 '22 09:09

laggingreflex