Skip to content
Related Articles

Related Articles

How to run node.js program as an Executable ?
  • Last Updated : 05 Jun, 2020

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.

  1. Add bin section in package.json
  2. Change index.js file permission (not for windows operating system).
  3. Add comment to index.js file to allow it to be treated like an executable.
  4. 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.
My Personal Notes arrow_drop_up
Recommended Articles
Page :