Why does starting my globally related npm package just open the bin file?

If I am developing the npm foo package and want it to be installed globally as a command-line application, I can do this simply by adding package.json to my package:

 "bin": { "foo": "./bin/foo.js" } 

Someone who installs my package worldwide through npm will have the corresponding batch file and shell script added to their global npm prefix. However, suppose I want to be able to run my package from the shell (or, in the case of Windows, the command line). I could do this by creating a batch file / shell script somewhere in one of my PATH directories, which simply runs my package directly, for example. @node C:\my\package\directory\bin\foo %* .

This is a fairly simple and obvious solution, but I felt that the npm link better suited because it feels less hacked and theoretically designed to accomplish this particular task. I run npm link in my package directory and then test it by running foo from the command line. Instead of running my script, however, foo.js actually opens in my default editor. Examining in the prefix directory, it turns out that the file foo.cmd (the contents of the shell foo script) that npm created contains the following:

 "%~dp0\node_modules\foo\bin\foo.js" %* 

Compare with the batch file created by npm install -g :

 @IF EXIST "%~dp0\node.exe" ( "%~dp0\node.exe" "%~dp0\node_modules\npm\bin\npm-cli.js" %* ) ELSE ( @SETLOCAL @SET PATHEXT=%PATHEXT:;.JS;=;% node "%~dp0\node_modules\npm\bin\npm-cli.js" %* ) 

Why does npm link create script files that run the package bin file instead of running node with the bin file as an argument? How can I fix this behavior?

+6
source share
2 answers

The solution is to add #!/usr/bin/env node at the beginning of your bin script. However, I have no idea why. I found out by comparing my script with others that worked.

+5
source

What version of npm are you using? The latter is 2.6.0, there have been many improvements recently for npm - especially around conflicts and race conditions during installation. Can you try updating the npm installation?

To upgrade npm on Windows, follow these steps: https://github.com/npm/npm/wiki/Troubleshooting#upgrading-on-windows

0
source

Source: https://habr.com/ru/post/983002/


All Articles