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

I plan to do something similar, like custom lodash assemblies. Therefore, in general, I want the user to write a command, for example:

lodash category=collection,function 

Creating a custom module with only the specified category i

I read several tutorials on 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 to the fragment of the command, and when I write it, it runs the script index.js in the bin folder.

This part looks correct to me. When I have something simple in my index.js ie console.log('It Works') .

In a standard situation, you want the user to pass parameters to the script. Therefore, I found out that all parameters should be in the variable process.argv .

The process.argv property returns an array containing the command line arguments passed when the Node.js process started. The first item will be process.execPath. The second element is the path to the JavaScript executable. The remaining elements will be any additional command line arguments.

So, I just console.log and run the script.

  • If I run the script using the snippet -f -a command Output: [ 'node', 'path/to/file' ]

  • If I run the script through node bin/index.js -f -a Exit: [ 'node', 'path/to/file', '-f', '-a' ]

I do not understand that this is the same script, but a different conclusion. However, I try to make it look like when I call the script through the bin command, it never passes parameters.

Is it someone who has experience? And advise me what am I doing wrong?

Or alternatively is there another way to do this?

Thanks for the consultation.

+5
source share
1 answer

It takes time, but I have a solution, so I hope that it helps someone later.

Where was the problem:

I noticed that my windows have a default program to run the .js file installed on NODE.js , and because by default all .js files open without parameters.

So, in my case, every .js file is opened using NODE, no matter what, I try to change it to open something like PSPAD or similar, but this basic open editor is instead of an executable.

How I fixed this:

  • Instead of directly executing .js, I am making my binary ./bin/index.js (basically the remote suffix .js )
  • Added #!/usr/bin/env node on top of index file
  • Going to package.json and changing the whole dependency from ./bin/index.js to ./bin/index

Woala! it works:)

ps As I mentioned at the beginning, I believe that it is possible to run this using .js , but I could not find it. So please, if anyone finds this, let me know. Thanks

+1
source

All Articles