Packaging Node.js Applications into Executable Files with pkg
This tutorial explains how to use the pkg tool to bundle a Node.js script into a standalone executable for Windows, macOS, and Linux, covering installation, sample code, configuration, and command‑line options to distribute applications without requiring a separate Node.js runtime.
When you develop a Node.js program and want to distribute it to users who may not have Node.js installed, you can package the program into a single executable, which also helps protect the source code and APIs.
Several tools can achieve this, such as pkg , nexe , node-packer , and enclose ; for GUI applications you can use Electron.
Install pkg globally with:
npm install pkg -g
Create a simple Node.js library called prettyJson :
function pretty(filePath){
return JSON.stringify(JSON.parse(require('fs').readFileSync(filePath).toString()), false, 3);
}
console.log(pretty(process.argv[2]));Save the code as index.js , then initialize a package:
npm init -y
Package the script with pkg by specifying the entry file:
pkg index.js
By default, pkg downloads the latest Node.js source and builds binaries for Linux, macOS, and Windows (e.g., node12-linux-x64 , node12-macos-x64 , node12-win-x64 ).
The underlying pkg-fetch library retrieves the appropriate Node.js binary packages from the pkg-fetch releases , caches them locally, and reuses them on subsequent builds.
These binary packages hijack certain Node.js functions so that the executable can read bundled JavaScript and resource files.
After packaging you obtain three files, one for each target platform. The general command syntax is:
pkg [options] <input>You can specify the target platform with -t (e.g., -t node12-win-x64 ) and the output file with -o . A typical package.json configuration may include a bin field and a pkg section defining scripts, assets, and targets.
Dynamic require calls are not automatically bundled; you must list such files in the scripts and assets arrays using glob patterns.
Use the --debug flag to troubleshoot the packaging process.
Finally, run the generated executable without a Node.js environment, for example:
pkg -t node12-win-x64 -o prettyJson.exe index.js
This produces prettyJson.exe , which can be executed directly to format JSON files.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.