Create a globally executable javascript file

· 253 words · 2 minute read

We will understand and see how to create an executable javascript file using a global command.

Lets say for example you want to create a clone of ‘ls’ or ‘cmd’ command which shows the content of the current folder or from the path provided. To acheive that we need to have a global command.

To acheive this we need to do couple of things and need to have 2 files (index.js and package.json)

  1. index.js will have the code that you to execute when running the command
  2. package.json helps the binding the command to the index.js file
  1. Create the file index.js in your project folder
  #!/usr/bin/env node

  console.log("This file will be an executable file");

The first line in index.js #!/usr/bin/env node tells the system what interpreter to pass the file to for execution.

  1. create a package.json file using npm init –y and add the following lines
  "bin": {
    "nodemonclone": "index.js"

here nodemonclone will be the global level command (you can give it any name you want)

  1. The last step is to link nodemonclone to the index.js file so that the code inside index.js gets executed when we run nodemonclone

NOTE: For Mac/Unix users, you will need to change permission using below command of the index.js so it can be executed (if doesn’t work, try running with sudo).

 chmod +x index.js

and to link the file just run the command below from within your project folder.

 npm link

And all done. Now you can run nodemonclone and see the console.log output on your terminal.