EDDYMENS

Last updated 2022-09-04 05:59:58

Compile NodeJS To Executable

Table of contents

You can bundle your NodeJS project into a single executable program for several operating systems using the PKG CLI tool [↗]. This is a tool provided by Vercel [↗].

You do not need to be a customer of Vercel to use this tool as it is free and open source.

This is ideal for building and distributing CLI tools without requiring the end user to have NodeJS and your project dependencies installed.

You might also use it to deploy your application as a single binary onto your server which reduces your deployment steps.

PKG supports macOS, Windows (x64, arm64, armv6, armv7), and several flavors of Linux (alpine, Linux, Linuxstatic).

Installing PKG

PKG is an NPM package [↗]. You can install this globally and use it directly from the command line.

$ npm install -g pkg

Compiling for different operating systems

As mentioned earlier PKG supports multiple platforms. You can generate binaries for all supported operating systems using whichever operating system you are currently running.

It also supports compilation using different NodeJS versions with Node 8 being the least supported version. Again you don't need to have the Node version used in compilation installed locally.

To compile your project, CD into the project directory and run the following command:

$ pkg -t node12-linux,node14-linux,node14-win index.js -o output-name

This will generate the requested binaries within that directory.

Running the executable

Once compiled you can run your program like you would any executable. The generated binaries can be found in the directory where the compilation was performed.

$ ./output-name-node14-linux

How does it work?

During compilation, PKG fetches the requested or latest pre-compiled version of NodeJS for the respective platform. This is known as the "base binary".It contains everything needed to run your NodeJS application in isolation.

Your project files are then bundled together with the pre-compiled base binary to form the resulting executable.

If you happen to have assets/project files, not within the project directory, PKG will fetch and remap the path using a virtual directory structure. This ensures that your binary can be shipped without having issues with assets pulled in using absolute paths.

You can read more on all the available options PKG provides from its Project README page on GitHub [↗]

Here is another article you might like 😊 "Diary Of Insights: A Documentation Of My Discoveries"