Packaging node apps

By
Billy Davis

We like portable apps at liquidfish, but you will typically have a lot of dependencies with a node app. So, we were excited when we saw pkg from zeit.

pkg allows you to package your node project into a compiled app. Compiling your app has some great benefits including:

  • Make a commercial or demo versions of your application without sources
  • Instantly make executables for other platforms (cross-compilation)
  • No need to install Node.js and npm to run the packaged application

There are lots of use cases for this, one of ours is a tiny app that we can run to create and restore snapshots of droplets. If we deploy some breaking changes to an instance, we can roll back those changes quickly with a snapshot. This is a lifesaver when dealing with small quirky applications and allows us to minimize downtime on projects that don’t have sophisticated release cycles.

For example, we can run this app on any of our machines:


do-snapshot --droplet 12345678
Creating snapshot...
Done.

This will create a snapshot of the droplet 1234.

We can restore that snapshot like so:


do-snapshot restore --droplet 12345678 --snapshot 90123456
Restoring snapshot 90123456 on droplet 12345678...
Done.

You can run this by hand, from a scheduled AWS Lambda function or a good ol’ cron.

The build process is really simple. Let’s say you had this as `app.js`


console.log('Hello Fish');

Run this command:


pkg app.js


> Targets not specified. Assuming:
  node7-linux-x64, node7-macos-x64, node7-win-x64
> Fetching base Node.js binaries to: ~/.pkg-cache
  fetched-v7.6.0-linux-x64     [====================] 100%
  fetched-v7.6.0-macos-x64     [====================] 100%
  fetched-v7.6.0-win-x64       [====================] 100%

That's it.

Within your current directory, you will have three binaries:

  1. app-linux
  2. app-mac
  3. app-win.exe

So, you can run


./app-linux
Hello Fish

Boom.

All you need to do is drop the compiled app on the target machine and you are ready to go. No dependencies and time saved without having to run the npm install.