54

I found serval node.js projects that have this at top of their app.js (as in this openshift program):

#!/bin/env node

What does this mean? How does this work? Where is it useful?

Pranav 웃
  • 8,094
  • 5
  • 36
  • 48
hh54188
  • 13,085
  • 30
  • 99
  • 174

2 Answers2

65

The full line from your example is:

#!/bin/env node

This simply means that the script should be executed with the first executable named 'node' that's found in your current PATH.

The shebang (#!) at the start means execute the script with what follows. /bin/env is a standard unix program that looks at your current environment. Any argument to it not in a 'name=value' format is a command to execute. See your env manpage for further details.

sockmonk
  • 4,005
  • 22
  • 39
  • 1
    In general, do I need add this declare in my node app? – hh54188 Feb 25 '13 at 06:29
  • 2
    Only if you want to be able to start it using `./app.js` instead of needing to type `node app.js`. For an example where it's useful have a look at http://stackoverflow.com/questions/14517535/directly-call-globally-installed-node-js-modules – Golo Roden Feb 25 '13 at 08:03
  • 4
    Type 'which env' to get the path on your local system. It may be installed in /usr/bin/env instead, for example. – sockmonk Feb 18 '14 at 16:12
  • 3
    @chovy ... A bit late, but for osx I symlink env into bin: sudo ln -s /usr/bin/env /bin/env – Paul J Aug 14 '15 at 00:13
  • @AndrewLam #!/usr/bin/env node is the right spelling. Some platforms have /bin/env as well as /usr/bin/env, but those are typically because /bin is the same as /usr/bin. If you're asking whether that works on only linux/unix flavors vs. windows, it depends - if you use cygwin or other flavors of , then yes, that will work, but if you just want to execute from a windows explorer window or windows command prompt (or power shell) then the #! sequence to indicator what interpreter to use won't help. On both windows and unix, you can run 'node app.js' and whatever you have for #! is irrelevant. – Juan Jan 18 '19 at 18:18
7

env is a shell command used to specify an interpreter.

Chris Ledet
  • 11,190
  • 6
  • 37
  • 47
  • 15
    In plain English that means `env` will find the location of `node` in your $PATH. People sometimes do `#!/bin/node` or `#!/usr/local/bin/node` but the problem is, you don't know where the person may have their copy of node. So `env` program finds that for you. – Mauvis Ledford Feb 25 '13 at 06:19