Don Rhummy Don Rhummy - 3 months ago 9
Javascript Question

Is there a way to get the package.json properties in a module run from npm?

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.

Answer

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.

Comments