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

Get application full path in Node.js

Get application full path in Node.js

Problem

I'm wondering if there is a best way or best practice to get the full path of application in Node.js. Example: I have a a module in sub folder /apps/myapp/data/models/mymodel.js, and I would like to get the full path of the app (not full path of the file), which will return me /apps/myapp, how do I do that? I know _dirname or _file is only relative to the file itself but not the full path of the app.

Problem courtesy of: Nam Nguyen

Solution

There's probably a better solution, BUT this should work:

var path = require('path');

// find the first module to be loaded
var topModule = module;

while(topModule.parent)
  topModule = topModule.parent;

var appDir = path.dirname(topModule.filename);
console.log(appDir);

EDIT: Andreas proposed a better solution in the comments:

path.dirname(require.main.filename)

EDIT: another solution by Nam Nguyen

path.dirname(process.mainModule.filename)
Solution courtesy of: Laurent Perrin

Discussion

View additional discussion.



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

Share the post

Get application full path in Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×