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}`);
});
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 🙂
make exe then rar it. it will decrease file size to 1/4 only.
The only problem is that it generates HUGE files.
Exactly, my small bash script like nodjs script with 200 lines, loadash and inquirer has 39 mb somehow..
Agreed, but as I said in the post:
“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.”
I think there are plenty of use case where 40mb binary is fine, and ease of crating it cross platform is more important.
Excellent post.
Worth considering not to install pkg globally, rather as a dev dependency (npm i pkg –save-dev), and setup npm script such as:
“scripts”: {
“build-native”: “./node_modules/pkg/lib-es5/bin.js sk4.js”
}
And run with “npm run build-native”