How to Run Node.js Program as an Executable ?

Node.js allows you to create standalone executables from your JavaScript programs, making them easy to distribute and run on various platforms without requiring Node.js to be installed. This article will guide you through the process of converting a Node.js program into an executable file using popular tools like pkg, nexe, and pkg-conf.

Why Create Executables?

Running Node.js programs as executables offers several benefits:

  • Portability: Executables can be run on any system without the need for Node.js installation.
  • Distribution: Distributing executables simplifies deployment and ensures consistency across environments.
  • Security: Executables can be obfuscated and packaged securely to protect intellectual property.

Approach

  • Add bin section in package.json
  • Change index.js file permission (not for the Windows operating system).
  • Add comment to index.js file to allow it to be treated like an executable.
  • Link the project.

Step 1: Adding bin section in package.json file 

"bin" : {
"execute" : "index.js"
}

Note: Add any reasonable word in place of ‘execute’.

Step 2: Change the File permission  

chmod +x index.js

Step 3: Add comment to index.js  

#!/usr/bin/env node

Step 4: Command to link projects  

npm link

Example: Implementation to run node.js program as an executable.

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}`);

Take this as Input :

execute Countlengthofmine!

Output:  

Example 2: Implementation to run node.js program as an executable.

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}`)

Take this as Input :

execute Aasia

Output: