Make a Node.js Script Globally Executable with a Shebang and a Symbolic Link

Share this video with your friends

Social Share Links

Send Tweet

A CLI isn't super useful if you have to be inside of the project to start the script.

To fix this, we can add a #! (shebang) to the top of our entry file. On linux and MacOS systems you'll also have to make the file executable as well. Then we can use a symbolic link to add a custom quizme command to our path that points at our scripts entry file.

We'll need to fix one more thing though! If you try to run the script in a different directory, the file it references for ./data.json will be incorrect, we'll fix this in the next lesson.

Instructor: [0:00] I want to be able to use this by typing "quizme," but quizme doesn't exist as a local command. There are a few things I need to do to allow my operating system to be able to read this file as a command. [0:13] At the top of my file, I'm going to add an egg, a high shine, and an exclamation point. This is sometimes called a hashbang or a shebang. I'm going to follow that with what I want to execute.

[0:24] On Windows, I put Node. That's the command I want to use to execute this script. On OS X systems, I'm going to put /usr/bin/env node. On a Linux systems, I'll need to give the exact path to my executable, but for me, I'm running Node like this.

[0:44] Having added my shebang, I need to make my file executable. To do that, I'm going to change it to be executable. This is for Linux and Mac OS systems, index.js.

[0:57] Now I should be able to run my index.js, and it should run without me needing to say, node run this file. The shebang is saying, I need to use node to do this. 22, it's absolutely right, yes. Then, let's check our data file and make sure that the was the last question. Yep, the last question was 1. Brilliant.

[1:16] We've added the shebang or hashbang, and we've made the file executable. Now for the final step, I want to run quizme for this to execute anywhere in my file system. If I'm running Linux, the Linux subsystem in Windows, or MacOS, I can use a symbolic link with ln -s.

[1:32] I have to get the absolute path -- /users/kevin/code/egghead/quizme -- and where I want it to be. I'm going to put it in /usr/local/bin. This would be the index.js file, specifically /usr/local/bin. I'm linking that user.js file to a quizme command that's in my PATH.

[1:52] Now if I use quizme, according to the results Andorra, yes, and quizme --add. What's my question, "Did this work?" Hopefully. If we check, then, our data, "Did it work?" Hopefully.

[2:08] It feels like we're done, we have one more thing we need to fix. At the moment, it's working like our README is expecting it to. If I jump over to a different directory, say my /home directory, and try to run quizme there, I get an error that there's no such file, data.json, because when my script is executing, it's using this directory to decide where to find data.json.