Bundle a precompiled binary or native file into an electron app.

Ganesh Rathinavel
2 min readJan 26, 2019

--

Introduction

Distributing pre-compiled native binaries along with an electron application could get tricky as the ASAR packager tends to exclude such files while packaging the app. This was originally implemented inside OpenMTP — Advanced Android File Transfer Application for macOS.

Implementation

  • Create the “OS” folder inside the project’s “build” directory
# Replace {OS} with the required OS name. eg: mac, win, linux
$ mkdir -p ./build/{OS}/bin
  • Place the binaries here
  • Install npm packages
$ npm install electron-root-pathor$ yarn add electron-root-path
  • Create the file ./app/binaries.js and paste the code:
'use strict';import path from 'path';
import { remote } from 'electron';
import { rootPath } from 'electron-root-path';
import getPlatform from './get-platform';
const IS_PROD = process.env.NODE_ENV === 'production';
const root = rootPath;
const { getAppPath } = remote.app;
const isPackaged =
process.mainModule.filename.indexOf('app.asar') !== -1;
const binariesPath =
IS_PROD && isPackaged
? path.join(path.dirname(getAppPath()), '..', './Resources', './bin')
: path.join(root, './resources', getPlatform(), './bin');
export const execPath = path.resolve(path.join(binariesPath, './binary-file'));
  • Create the file ./app/get-platform.js and paste the code
'use strict';import { platform } from 'os';export default () => {
switch (platform()) {
case 'aix':
case 'freebsd':
case 'linux':
case 'openbsd':
case 'android':
return 'linux';
case 'darwin':
case 'sunos':
return 'mac';
case 'win32':
return 'win';
}
};
  • Add the below code to your ./package.json file
"build": {
"extraFiles": [
{
"from": "build/mac/bin",
"to": "Resources/bin",
"filter": [
"**/*"
]
}
],
},
  • To distribute the code via Mac App Store, add the below code to your package.json file
"build": {
"mas": {
"type": "distribution",
"category": "public.app-category.productivity",
"entitlements": "build/entitlements.mas.plist",
"icon": "build/icon.icns",
"binaries": [
"dist/mas/<APP_NAME>.app/Contents/Resources/bin/mtp-cli"
]
},
}
  • Import the binary file as:
import { execPath } from './binaries';// your program code:
var command = spawn(execPath, arg, {});

More repos

License

tutorial-electron-bundle-binaries is released under MIT License.

Copyright © 2018-Present Ganesh Rathinavel

--

--

Ganesh Rathinavel
Ganesh Rathinavel

Written by Ganesh Rathinavel

The J̶a̶v̶a̶S̶c̶r̶i̶p̶t̶ Dart Guy

No responses yet