Day 44 of #100DaysOfCode: Use Electron-packager to generate a Window installer for the Node.js application
Tags: javascript, node, webdev, electron
Published: 2020-11-05 09:32:05

## Introduction
[I have use electron-builder to build the installer for Django and React application](https://medium.com/a-layman/turn-the-next-js-django-website-to-the-desktop-app-and-generate-windows-macos-installers-db4b4c9ead61). This article is the note for generating the Windows installer for Node.js application by [electron-packer](https://www.npmjs.com/package/electron-packager).

## Steps
### 1. install packages

```
npm install -s electron electron-packager is-reachable
```

### 2. Modify package.json

```
{
    ...
    "main": "main.js",
    "build": {
        "extends": null,
        "win": {
          "target": "portable"
        },
        "asar": false,
        "files": [
          "./main.js"
        ]
     }
    ...
    scripts": {
        "dist_win32": "electron-packager . Win32App --platform=win32 --arch=x64 --overwrite"
    }
}
```
### 3. Create preload.js

```javascript
const _setImmediate = setImmediate;
const _clearImmediate = clearImmediate;
process.once('loaded', () => {
  global.setImmediate = _setImmediate;
  global.clearImmediate = _clearImmediate;
});
```

### 4. Create main.js

* server.js is the entry file Node.js server

```javascript
// Modules to control application life and create native browser window
const {app, BrowserWindow} = require('electron');
const path = require('path');
const url = require('url');
const cp = require('child_process');
const isReachable = require('is-reachable');
const contants = require('./constants.js');
const logFilePath = contants.logFilePath;
const logger = require("pino")(logFilePath);
const port = process.env.PORT || 8000;

const startAdonis = () => {
  cp.execFile('node', [`${path.join(__dirname,'server.js')}`]);
};

const createWindow = () => {
  
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 1200,
    height: 1000,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  });
  // and load the index.html of the app.
  mainWindow.loadURL(`http://localhost:${port}/index`);

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
};

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async() => {
  startAdonis();
  while(!await isReachable(`http://localhost:${port}`)) {
    logger.info('wait for the node.js server');
  }
  createWindow();
  
  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  });
});

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
``` 

### 5. Generate the Windows installer

```
npm run dist_win32
```

That's it!

## Articles
There are some of my articles. Feel free to check if you like! 
* [My blog-posts for software developing](https://medium.com/a-layman)
* [My web resume](https://jenhsuan.github.io/ALayman/cover.html)
* [Facebook page](https://www.facebook.com/imalayman)
* [Twitter bot](https://twitter.com/ALayman84368087)