Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js, how can a module get data from an application's package.json?

Tags:

json

node.js

npm

I have a module. Inside it, I'd like to access data from my parent application's package.json file. What's the best practice way to do that?

I've done this the janky way by going up 2 levels and requiring the file (or using the nconf configuration loader).

var appdir = path.resolve(__dirname, '../../');
nconf.file('app', path.join(appdir, 'package.json'));

But that seems like it could break easily.

Also I heard about pkginfo, it will automatically grab info from my own module's package.json, but I'm looking to get data from the parent application's.

Thanks for any help!

EDIT: I suppose another way of asking is, how can I get the application's path (instead of the module path) ?

like image 609
dylanized Avatar asked Apr 30 '13 13:04

dylanized


1 Answers

You can use

require.main.require './package'

But it'll work only if your parent application's file is in a root of it's directory.

You can also wrap it into try ... catch and add ../ to path till you find package.json.

You can read more about accessing main module here http://nodejs.org/api/modules.html#modules_accessing_the_main_module

like image 190
prcu Avatar answered Oct 24 '22 09:10

prcu