How to build an executable with NodeJS
The tool that lets us do it, is called pkg and is located at https://www.npmjs.com/package/pkg
Introduction
It's a great day, you've build a simple node app that gets weather info from an API and display the information to
the console. You have called the app weather.js, and obviously you run it like this: node weather.js
.
There are 2 downsides for this approach, first and foremost, you need node installed in your computer along with
node modules (if your app requires them). So the distribution of your app is limited to only those who have node
installed (that's bad). Finally your app is not directly callable with a double click, you need first to open cmd
and then run it. These 2 downsides limit your power to reach undiscovered grounds, so i'm here to change the way you look at node.
Why
- Make a commercial version of your application without sources
- Make a demo/evaluation/trial version of your app without sources
- Instantly make executables for other platforms (cross-compilation)
- Make some kind of self-extracting archive or installer
- No need to install Node.js and npm to run the packaged application
- No need to download hundreds of files via npm install to deploy your application.
- Deploy it as a single file
- Put your assets inside the executable to make it even more portable
- Test your app against new Node.js version without installing it
How
Well let's get started, take note that we are not going to use ES6 and we are on Windows.
# Create a new folder
mkdir node-pkg
# Move into the folder
cd node-pkg
# Initialize your project
npm init
Now let's install a module that brings nice dialog boxes to javascript
Make sure you've installed all the necessary build tools (https://github.com/nodejs/node-gyp#installation) for your platform, then invoke:
npm install mitsobox --save
Within the root directory, create an index.js file and use this code
'use strict';
var mitsobox = require('mitsobox');
mitsobox.OK('Hello from node!', 'Just the title here');
Now install pkg globally
npm install -g pkg
Now build your app
pkg index.js --output myApp.exe
Look at your folder now, the executable is there, waiting for you to distribute it across the globe. Consider contributing to my mitsobox project on github :) https://github.com/jimfilippou/mitsobox
Thanks for reading!