I'm trying to create a node module that has the ability to be installed globally using npm install -g mymodulename
. I've got everything in the module working fine if I run node index.js
in the directory of the module, but now I want to make it so that I can publish it to NPM, and it can be installed and run from any directory.
There is some code in my module that looks at certain files in the directory that it is run in. I'm finding that when I do npm install -g ./
and then go into a different directory for a test, then run my-module-command
, the relative path that it is reading is from that of where my module got installed (i.e. /usr/local/bin/my-module
), not the directory that I'm running it in.
How can my module that is installed globally know where it is being run from? To give an example, I am trying to read the package.json
file in the directory I'm in. And it is reading the package.json
file of /usr/local/bin/my-module/package.json
I've tried:
__dirname
process.args[1]
process.cwd()
And just calling straight to require('./package.json')
directly and none of those work.
Edit here's some code that's breaking in index.js
:
#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var currentDir = path.dirname(require.main.filename);
fs.exists(`${currentDir}/node_modules`, function(dir) {
if (!dir) throw 'node_modules does not exist';
// do stuff
});
In my package.json
:
...
"bin": {
"my-module": "./index.js"
},
...
I try to do npm install -g ./
in the project directory, and then I cd into a different directory called /Users/me/Projects/different-project
, where another npm project is, and run my-module
, and I get node_modules does not exist
. When I log out currentDir
, I get /usr/local/lib/node_modules/my-module
where I'm expecting is to see /Users/me/Projects/different-project
.