How to run node.js program as an Executable ?
Last Updated :
05 Aug, 2022
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
#!/usr/bin / env node
const word = process.argv[2];
const length = word.length;
console.log(`Words Length : ${length}`);
|
Input
execute Countlengthofmine!
Output:
Example 2:
Javascript
#!/usr/bin / env node
const name = process.argv[2]
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.
Share your thoughts in the comments
Please Login to comment...