Making a binary from Node.js scripts

By Peter West • 22nd December 2019 21:28

I often find myself needing to package a Node.js project as a single binary file, i.e. turn the source tree into a single self-executable file.

There are a few tools which can be used to do this, such as pkg. However, pkg does not work with binary modules, such as the sharp module for image manipulation.

In the end, I wrote my own script to generate a self-executing binary based on a Linux Journal article on bash self-extracting scripts. This works as follows:

  1. Package the source tree, node binary, and node modules in a tar.gz (the payload).
  2. Append the payload to the end of a shell script. When executed, the script extracts and runs the payload in a temporary location.

Here is the code (only tested on linux):