Nick Manning
Nick Manning

Reputation: 2989

I'm learning about shebangs. How do I make it work with node.js in a Mac terminal?

I have:

#!/usr/bin/env node
console.log("It works!");

I learned that env finds the node program and interprets it with node. I checked that env exists in /usr/bin.

When I call node itworks.js it works and outputs It works!. However, from what I understand, I should just be able to call itworks.js without node due to the shebang. But when I make this command it says -bash: itworks.js: command not found.

Could someone help me get the shebang to work?

Upvotes: 2

Views: 106

Answers (2)

cdarke
cdarke

Reputation: 44364

The reason for :

-bash: itworks.js: command not found

is because bash looks for programs in directories in the PATH environment variable when you do not say where the file is - it does not look in the current directory unless you tell it.

You could update the PATH variable with the current directory shortcut ., but that can be a security risk, so most run the program like this:

./itworks.js

Of course if you put your scripts all in one directory then you could add that to PATH in one of your start-up files. For example, if you had a directory called bin in your home directory that held your scripts:

PATH=$PATH:"$HOME/bin"

You also need to add the execute permissions to the script:

chmod u+x itworks.js

The u indicates that we only give permission for the current user to execute this file. If we omit the u then anyone can run it.

Upvotes: 0

slebetman
slebetman

Reputation: 113906

First of all you need to make the file executable:

chmod +x itworks.js

Then you need to call it by specifying the path as well. Either:

/where/it/is/on/disk/itworks.js

or:

./itworks.js

Upvotes: 5

Related Questions