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 reasonable 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:
Javascript
// Adding comment 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:
Javascript
// Adding comment 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 do the above-mentioned 4 steps to run your node.js program as executable.
- For Windows users, run the Executable from Node.js command prompt.
Please Login to comment...