2

I'm writing a module will will be run from a "scripts" property like this:

"scripts": {
    "runMyModule": "mymodule -stuff stuff"
}

NOTE: This is not the package.json of my module. This is the package.json the user uses to run npm.

I want to allow them to add a property to that main package.json file (which at the command line they execute by npm run runMyModule) which my module will then read. Is this possible?

I want something like:

"forMyModule": {
    stuff: [
        "one",
        "two"
    ]
},

"scripts": {
    "runMyModule": "mymodule -stuff stuff"
}

Is it possible in my module to get the forMyModule.stuff?

I've created both the index.js and bin/mymodule.js files.

mscdex
  • 104,356
  • 15
  • 192
  • 153
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330

2 Answers2

5

Find the root path of the project that uses your module. There are several ways to do this, each with its pros and cons: Determine project root from a running node.js application

Once you have that path, you can simply require(path.join([rootPath, 'package.json'])) and inspect the contents to find the settings.

Community
  • 1
  • 1
Jeroen Noten
  • 3,574
  • 1
  • 17
  • 25
  • 1
    Thank you. I used the link and your suggested code to use `var settings = require( process.cwd() + "/package.json" );` – Don Rhummy Aug 09 '16 at 23:45
0

Would something like this work for you?

var pjson = require('../package.json');
console.log(pjson.forMyModule);
Mike Lambert
  • 1,976
  • 1
  • 17
  • 31
  • I believe so? Globally installed modules have the same directory layout inside a node_modules/ directory, just with a different path (global) prefix. – Mike Lambert Aug 09 '16 at 23:38
  • Not work on every case, using webpack, you can get a error: Module not found: You attempted to import ../../package which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. – rodrix Mar 15 '19 at 00:13