Teemu Ikonen
Teemu Ikonen

Reputation: 11929

How to get details of npm installed modules programatically?

Is there way or library that could tell where from require'd module was resolved and especially what binaries it possibly contains?

For example, when I require('coffee-script') there is (AFAIK) no way to tell its installation directory and what command line binaries it has.

What I ideally need is some kind of mix between require and package.json parser, e.g. like following hypotethical 'npminfo' library.

var npminfo = require('npminfo')

// get info about module
var pkginfo = npminfo.resolve('coffee-script')
pkginfo.version => '1.1.0'
pkginfo.path  => '/home/teemu/node_modules/coffee-script'
pkginfo.bins =>  { coffee: '/home/teemu/node_modules/coffee-script/bin/coffee', cake: '/home/teemu/node_modules/coffee-script/bin/cake'}

// generic info
npminfo.binpath => '/home/teemu/.node_modules/bin' 

I did try to use require.paths and just walk through directories, but for some reason it does not contain path where my modules are actually installed. Somehow require still finds them though?

~ $ node
> require.paths
[ '/Users/teemuikonen/.node_modules',
  '/Users/teemuikonen/.node_libraries',
  '/usr/local/lib/node' ]
>

~ $ ls /usr/local/lib/node
wafadmin

~ $ ls .node_modules/
ls: .node_modules: No such file or directory

~ $ ls node_modules/
cli  cradle coffee-script ...   

Thanks

Upvotes: 4

Views: 2781

Answers (1)

Chris Biscardi
Chris Biscardi

Reputation: 3143

use require.resolve('module') to get the path

require looks for a folder called node_modules at each level. This isn't displayed in require.paths(), but I'm not sure why.

Update: this will log the files in the modules folder

var fs = require('fs');
var path = require('path');
var path1 = require.resolve('module');
path1 = path.dirname(path1);
fs.readdir(path1, function(err, files){
  console.log(err);
  console.log(files);
})

Upvotes: 7

Related Questions