Tech TLDR;

  • Archive
  • Top Posts
  • GitHub
  • LinkedIn
  • Contact

Compile Node.js to Native Binaries

May 1, 2017 by admin

Guillermo Rauch (Socket.io, Mangoose.js, Hyper.js, Now) is the guy to watch, and last night he did not disappoint. The following tweet announced pkg – a simple tool to generate a native executable file from Node.js code targeting Mac, Linux, and Windows.

Introducing `pkg`

Single command binary compilation for Node.js pic.twitter.com/Dbe9L1gb0x

— ZEIT (@zeithq) April 29, 2017

To try it out, I decided to re-implement the ls -alh command, that would display all files in the current folder, as well as their size in a human readable format.

Node already supports getting a list of files fs.readdirSync and their size fs.statSync.

I’ve installed a 3rd party library called filesize to convert the byte sizes to a human readable format.

The final program – ls.js – only took me 5 minutes to write and looked as such:

const fs = require('fs');
const filesize = require('filesize');

var files = fs.readdirSync('./');
files.forEach(file => {
  let fsize = filesize(fs.statSync(file).size)

  console.log(`${file} - ${fsize}`);
});

Code language: JavaScript (javascript)

Next I installed pkg, via npm install -g pkg.

Finally, I ran the pkg ls.js command to generate the binaries. Since I didn’t specify a specific target, pkg built binaries for 3 default platforms – Mac, Linux, and Windows.

I’ve run my generated executable ./ls-macos and got the following output:

The generated files are kind of big, but considering how easy it was to generate a binary while leveraging npm, I think it is a worthy trade off. I am excited about the project and see a lot of potential.

May be next time my mom is having a computer problem, I can send her a binary to execute 🙂

Filed Under: JavaScript, Node.Js, Tools

Copyright © 2023 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in