Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Main and renderer processes

A process is a separately running program with its own memory. An Electron app runs as several processes: one main process and one renderer process for each window. You need to understand this split from the start, because it decides where each piece of code goes.

The main process

The main process is Node.js. It starts first, from the file named in the main field of package.json, usually main.js. There is one main process per app. It:

  • creates and closes windows;
  • controls the app's life: startup and exit;
  • works with files, menus, dialogs and the tray;
  • can use any Node.js and npm module.
// main.js
const { app } = require('electron');
 
app.whenReady().then(() => {
  console.log('Main process started');
});

The main process's console.log output appears in the terminal you started the app from.

The renderer process

The renderer process shows the content of a window. It is an ordinary Chromium tab: HTML, CSS, the DOM, fetch. By default it has no access to Node.js.

// renderer.js
document.querySelector('h1').textContent = 'Notes';
console.log('Page loaded');

This console.log is not in the terminal but in the window's developer tools — DevTools, just like in a browser.

The preload script

A third participant stands between them — the preload script. It runs in the renderer process before the page loads and can hand the page a few safe functions. It is covered in detail in the "The page and IPC" chapter.

Runs inFile in the courseAccess
Main processmain.jsNode.js and the whole Electron API
Preload scriptpreload.jsA limited set of Electron modules
Renderer processrenderer.jsBrowser APIs only

Why they are separate

  • Reliability. If a page hangs or crashes, the main process and the other windows keep working.
  • Security. A page may show text or an image from the internet. If it had access to Node.js, a malicious script could delete the user's files. So the page asks the main process to perform an action, and the main process decides whether to allow it.

Messaging between processes is called IPC (inter-process communication). It has its own lessons.

Common mistake

Beginners write const fs = require('fs') in renderer.js and get require is not defined in the console. This is not a bug but protection: the page does not see Node.js. File work is done by the main process, and the page calls it through preload and IPC.

Thanks for reading!

Donate to the site — we work hard for you.