Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Nodejs get directory of `required` module

Nodejs get directory of `required` module

Problem

Is it possible to determine the Directory where required scripts come from?

My ultimate goal is to...

// return the directory where `mysql` module is found
var mysqldir = requiredir('mysql')
if(fs.existsSync(mysqldir+"/README.md")){
  console.log(fs.readFileSync(mysqldir+"/README.md").toString())
}

So I can have a handy reference for all these modules, and hopefully people in the enlightened future, will include Module docs/cheatsheets intended to be accessed in this manner

Problem courtesy of: Billy Moon

Solution

required.resolve(...) may be what you're looking for:

function requiredir(id) {
    return path.dirname(require.resolve(id));
}

Though, this will follow the main setting:

> requiredir('grunt')
.../node_modules/grunt/lib/

Another option may be to use npm's view, though this is limited to registered packages:

npm.load({}, function (err) {
    npm.commands.view(['mysql', 'readme'], true, function (err, readme) {
        console.log(readme);
    });
});
Solution courtesy of: Jonathan Lonowski

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Nodejs get directory of `required` module

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×