Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run npm {bin: script.js} with parameters

I am planing to make something similar as lodash custom builds. So in general I want to let user write command like:

lodash category=collection,function

Which create custom module just with category i specified

I read few tutorials how to run scripts with npm bin. Just in case I understand something wrong I write it what i think.

So if I have package.json with this part:

"main": "bin/index.js",
 "bin": {
   "snippet": "bin/index.js"
 },

and I npm install -g console should listen for command snippet and when i write it it run the script index.js in folder bin.

This part looks it works correctly for me. When i have something simple in my index.js i.e. console.log('It Works').

In standard situation you want to let user pass parameters to script. So i found out that all parameters should be in variabile process.argv.

The process.argv property returns an array containing the command line arguments passed when the Node.js process was launched. The first element will be process.execPath. The second element will be the path to the JavaScript file being executed. The remaining elements will be any additional command line arguments.

So i simply console.log it and run script.

  1. If I run script via command snippet -f -a Output is : [ 'node', 'path/to/file' ]

  2. If i run script via node bin/index.js -f -a Output is: [ 'node', 'path/to/file', '-f', '-a' ]

I dont understand that, its same script but different output. However I try it looks like when i call script via bin command it never pass parameters.

Is here someone who have experience with this? And advise me what i am doing wrong?

Or alternativly is there some other way how to make this?

Thanks for any advise.

like image 264
Andurit Avatar asked Aug 09 '16 08:08

Andurit


1 Answers

It take a time however I have a solution now so hope it help someone later.

Where was a problem:

I noticed that my windows has default program to run .js file set to NODE.js and because it's default setting of course all .js files are opening without parameter.

So in my case every .js file open with NODE no matter what, I try to changed it to open with something like PSPAD or similar but this basicly open editor instead of execute file.

How did I fix it:

  1. Instead of using executing .js directly with something I make my ./bin/index.js binary file (basicly removed .js suffix)
  2. Added #!/usr/bin/env node on top of index file
  3. Goes to package.json and changed all dependency on ./bin/index.js to ./bin/index

Woala! it works :)

p.s. As I mentioned at start I believe there is an option to run this with .js as well but I wasn't able to find it. So please if anyone will find it let me know. Thanks

like image 107
Andurit Avatar answered Sep 19 '22 11:09

Andurit