How to run node.js program as an Executable ?
Running Node.js program as an Executable means we do not have to go to the program directory, from anywhere in the terminal, we can execute our program with a specific self-registered word.
There are four steps to follow to run a node.js program as Executable.
- Add bin section in package.json
- Change index.js file permission (not for windows operating system).
- Add comment to index.js file to allow it to be treated like an executable.
- Link the project.
Adding bin section in package.json file:
"bin" : { "execute" : "index.js" }
Note: Add any resanable word in place of ‘execute’.
Change File permission
chmod +x index.js
Add comment to index.js
#!/usr/bin/env node
Command to link projects
npm link
Example 1:
// Adding comment to to index.js #!/usr/bin / env node // Code to count length of word // passed as argument // Receive argument via command line const word = process.argv[2]; // Counting length const length = word.length; // Printing it to console console.log(`Words Length : ${length}`); |
Input
execute Countlengthofmine!
Output:
Example 2:
// Adding comment to to index.js #!/usr/bin / env node // Receiving name as command // line argument const name = process.argv[2] // Say greetings console.log(`Hi there, ${name}`) |
Input
execute Aasia
Output:
Note:
- One must have to done the above mentioned 4 steps to run your node.js programme as executable.
- For windows user, run the Executable from Node.js command promt.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.