Reputation: 13270
I made a javascript file mytool.js
, it has some dependencies (in package.json).
Now I can execute typing in
~/mynodes/mytool $ node mytool
But if I change the working directory I can't use this command anymore because previously it was run locally. What I want to achieve is to be able to just type :
~$ mytool
(wherever I am in my system's filesystem and without typing node
before).
Should I install it manually ?
If yes, where is the common location to install a personal nodejs script in a unix-like system ?
Or is there a npm-like command to install a personal script system wide ?
Upvotes: 1
Views: 190
Reputation: 630
First option:
You can run your file globally by putting on the first line of the file : #!/usr/bin/env node
, copying it to /usr/local/bin
and make it executable: sudo chmod +x /usr/local/bin/yourfile.js
and then you can call it from where you want with yourfile.js
Second option:
Make your local file executable and create an executable bash script which calls your local file and put it in /usr/local/bin
and then call the bashfile globally.
Upvotes: 1
Reputation: 111336
When you add a "bin" key in your package.json:
"bin": {
"mytool": "mytool.js"
},
then you will be able to install your script with npm install -g
and it will be automatically added where it should be (to a place where other globally installed cli tools are installed, which should be in your PATH).
You can see this simple project as an example:
It was created as an example for this answer but it does what you need:
Note that you don't need to publish your script to npm to be able to install it - though you can do it, or you can also install projects directly from GitHub (including private repos) - but you can also install a module that you have in your local directory or a tarball:
npm install -g module-on-npm
npm install -g user/repo-on-github
npm install -g /your/local/directory
npm install -g /your/local/tarball.tgz
For more options, see:
Also keep in mind that for your program to be able to be executed from anywhere, you need to use paths relative to __dirname
or __filename
if you need to access your own files relative to your code. See:
Upvotes: 2
Reputation: 943518
#!/usr/bin/env node
).$PATH
chmod +x /usr/local/bin/example.js
)Upvotes: 1