Skip to content

Instantly share code, notes, and snippets.

@abelcallejo
Last active May 5, 2022 06:56
Show Gist options
  • Save abelcallejo/6b98ab8acc70b9441601c0c940ca1988 to your computer and use it in GitHub Desktop.
Save abelcallejo/6b98ab8acc70b9441601c0c940ca1988 to your computer and use it in GitHub Desktop.
Node + Electron cheatsheet

Node + Electron cheatsheet

Cloning an app

cd /path/to
git clone [email protected]:user/project.git
cd project
npm install electron --save-dev

Starting an app

npm start

Packaging an app

npm run build

Electron Packager

Installation

cd /path/to/dsi
npm install --save-dev electron-packager

Packaging

MacOS

cd /path/to/app
npx electron-packager ./ --platform=darwin --icon=icons/mac/Icon.icns

Windows

NOTE: When you are building a Windows package using a Mac machine, you will be required to install Wine.

brew install --cask wine-stable
cd /path/to/dsi

# 64-bit
npx electron-packager ./ --platform=win32 --arch=x64 --icon=icons/windows/Icon.ico

# 32-bit
npx electron-packager ./ --platform=win32 --arch=x32 --icon=icons/windows/Icon.ico

Message passing

Main to Renderer

Main

/**
 * `window` is an object which is an instance of `BrowserWindow`
 */
window.webContents.send( 'the-communication-channel', { 'message': "some message", 'someAttribute': 'some attribute' } );

Preload

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld('ipcPreload', {
	handle: ( channel, callable, event, data ) => ipcRenderer.on( channel, callable( event, data ) )
} )

Renderer

ipcPreload.receiveMessage('the-communication-channel', ( event, data ) => function( event, data ) {
	console.log( data ) // { 'message': "some message", 'someAttribute': 'some attribute' }
}, event);

Renderer to Main

Renderer

ipcPreload.send( 'the-communication-channel', { 'message': "some message", 'someAttribute': 'some attribute' } )

Preload

const { contextBridge, ipcRenderer } = require('electron')

contextBridge.exposeInMainWorld( 'ipcPreload', {
	send: ( channel, data ) => ipcRenderer.invoke( channel, data )
} )

Main

ipcMain.handle( 'the-communication-channel', async ( event, data ) => {
	console.log( data )
} )

Spawn

Executing a command

let commandCall = spawn( 'whois', commandArguments );

/** stdout **/
commandCall.stdout.on('data', (data) => {
	console.log( `${data}` ) // shows a good output
});

/** stderr **/
commandCall.stderr.on('data', (data) => {
	console.log( `${data}` ) // shows an error
});

/** After end of execution **/
commandCall.on( 'close', (code) => {

	let type = 'failed';

	/** The command exited successfully until the end **/
	if( parseInt( `${code}` ) == 0 ) {
		type = 'done';
	}

	console.log( type )
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment