Run node app as single executable file on Windows, Mac or Linux

With Pkg you can package your node application into a single executable for Windows, Linux or Mac. You will then be able to run the app without the need of installing node.

Install pkg globally:
npm install -g pkg

What we need is to specify in package.json the file starting the application with “bin”: “file.js”, and eventually the assets to include in the executable, under “pkg”. Here I include all the dependencies. This is my package.json file:

{
“name”: “test-app”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“bin”: “bin.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1",
“start”: “node bin.js”
},
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“axios”: “⁰.18.0”,
“diskusage”: “¹.1.1”,
“node-powershell”: “⁴.0.0”,
“os”: “⁰.1.1”,
“tasklist”: “³.1.1”
},
“pkg”: {
“assets”: [
“./node_modules/axios/**”,
“./node_modules/diskusage/**”,
“./node_modules/node-powershell/**”,
“./node_modules/os/**”,
“./node_modules/tasklist/**”,
“./node_modules/diskusage/**”
]
}
}

To create the executable for windows we can run the below command at the project root:

If we get an error message that some file cannot be included in the executable, we will have to distribute the file along with the executable in the same folder. For example I get the error message:

> pkg@4.3.8
> Warning Cannot include addon %1 into executable.
The addon must be distributed with executable as %2.
C:\Users\user\Documents\test-app\node_modules\diskusage\build\Release\diskusage.node
path-to-executable/diskusage.node

then I will just copy diskusage.node in the same folder where I will store the executable .exe file and distribute the folder. When we receive the above type of error, it does not prevent the executable file from being created.

In the command used to create the executable we can specify the target according to:
- nodeRange node${n} or latest → In our case was node10
- platform freebsd, linux, alpine, macos, win → In our case win
- arch x64, x86, armv6, armv7 → In our case x64

For more information check: https://www.npmjs.com/package/pkg.

If this tutorial helped you, you can thank me by buying me coffee.

--

--

Web development, CS and other stuff

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store