Skip to content
Related Articles
Open in App
Not now

Related Articles

How to run node.js program as an Executable ?

Improve Article
Save Article
Like Article
  • Last Updated : 05 Aug, 2022
Improve Article
Save Article
Like Article

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 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.

 

My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!