CLI with nodejs

2019-05-11 13:35发布

问题:

I'm developing a CLI in node that will be published to NPM. Since it's a CLI application, I want it to be included in the path once it's installed, so it's not require to type "node my-app.js" to run it. I want it to run with only "my-app".

In the package.json, I'm including:

"bin": { 
    "my-all" : "./my-app.js" 
 },

But this makes fail the installation via NPM with this error

Error: ENOENT, chmod '/home/user1/node_modules/my-app/my-app'

回答1:

Assuming you're on some kind of unix (linux, osx), put this line at the top of your script:

#!/usr/bin/env node

Also make sure you set the file to executable (chmod a+x my-all).

That should take care of the need to type node my-app.js, and enable you instead to just type ./my-app.js.

As for the npm packaging stuff I am not sure why it fails, but I'm guessing it's an issue with the path or location of your my-app.js .

If an executable script is put anywhere in the PATH, then it will be run just like anything else. If you run which npm, you will see where the npm executable script is located. On my system, most node executable (or executable npm scripts) goes into /usr/local/bin. I'm assuming your package.json can be set to put it somewhere in the path. If you need to change the path, then modify your .profile, or alternatively your system path.