Jordan Morris Jordan Morris - 3 months ago 10
Node.js Question

How to get npm package to have working scripts in .bin when installed?

I'm writing a nodejs commandline tool. When I test by running

npm install
and trying to run it locally, npm creates the following files in node_modules/.bin:




node_modules/.bin/myapp
containing:

"$basedir/../myapp/dist/myappcli.js" "$@"
exit $?





node_modules/.bin/myapp.cmd
containing:

"%~dp0\..\myapp\dist\myappcli.js" %*





They aren't very useful.

On the other hand, when I install popular nodejs cli tools, such as js-yaml or typings, I get much more useful files:




node_modules/.bin/typings
containing:

#!/bin/sh
basedir=`dirname "$0"`

case `uname` in
*CYGWIN*) basedir=`cygpath -w "$basedir"`;;
esac

if [ -x "$basedir/node" ]; then
"$basedir/node" "$basedir/../typings/dist/bin.js" "$@"
ret=$?
else
node "$basedir/../typings/dist/bin.js" "$@"
ret=$?
fi
exit $re





node_modules/.bin/typings.cmd
containing:

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





These actually successfully run their apps. Why do they get this fancy stuff? How can I make my app provide this? Do I have to manually add files into a tgz before uploading it to an npm host? I hope not, because I want to be able to install my app straight from github, or at least have npm pack generate the final, complete tgz.

Thanks

Answer

Add the following line to the very top of the javascript file which serves as the entrypoint for your command line application:

#!/usr/bin/env node

Thank you to jmir for this answer.