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

I have a module. Inside this, I would like to access data from my parent package package.json. What is the best way to do this?

I did it in a janky way, going up 2 levels and requiring a file (or using the nconf configuration loader).

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

But it looks like it could break easily.

I also heard about pkginfo , it automatically grabs information from my own package.json module, but I want to get data from the parent application.

Thanks for any help!

EDIT: I assume another way to ask the question is: how can I get the path to the program (instead of the path to the module)?

+5
source share
3

require.main.require './package'

, .

try ... catch ../ , package.json.

http://nodejs.org/api/modules.html#modules_accessing_the_main_module

+4

pcru, :

function loadMainPackageJSON(attempts) {
  attempts = attempts || 1;
  if (attempts > 5) {
    throw new Error('Can\'t resolve main package.json file');
  }
  var mainPath = attempts === 1 ? './' : Array(attempts).join("../");
  try {
    return require.main.require(mainPath + 'package.json');
  } catch (e) {
    return loadMainPackageJSON(attempts + 1);
  }
}

var packageJSON = loadMainPackageJSON();

, , , , , , , , package.json , , npm run-script

+2

node.js, process.cwd(), , js . node app/main.js cd app && node main.js .

module.parent, module.filename, module.parent undefined. . , script package.json . , script , , , - "bin", "app" "lib". , , package.json, , pkginfo, package.json .

+1

All Articles