Table of Contents
Key Takeaways
Installing Electron
You Need a Hero
Packaging the Application
Further Steps
Frequently Asked Questions about Desktop Node Apps with Electron
What are the prerequisites for developing desktop apps with Electron?
How do I install Electron on my system?
How do I create a new Electron project?
What is the structure of an Electron application?
How do I run my Electron application?
How can I package my Electron application for distribution?
Can I use Node.js modules in my Electron application?
Can I use web technologies in my Electron application?
How can I debug my Electron application?
Can I build cross-platform applications with Electron?
Home Web Front-end JS Tutorial Create Cross-Platform Desktop Node Apps with Electron

Create Cross-Platform Desktop Node Apps with Electron

Feb 18, 2025 pm 12:26 PM

Create Cross-Platform Desktop Node Apps with Electron

Key Takeaways

  • Electron, a tool developed by GitHub, allows developers to create cross-platform desktop apps using JavaScript and web technologies. It offers a more stable and secure solution than previous options such as Flash, Air, Java and Silverlight.
  • An Electron project requires three files: index.html, main.js, and package.json. The index.html file is the web page rendered by default, the main.js file starts the app and creates a browser window to render HTML, and the package.json file lists the application dependencies, metadata and files needed.
  • Electron apps can be packaged into ‘native’ applications using tools like the electron-packager npm module. This creates an executable binary that can run on various platforms, including Windows, macOS, and Linux.
  • Electron is not just for simple apps. It can handle complex functionalities and offers access to features like clipboard access, application menu bar tools, and the Chrome Dev Tools for debugging. Several popular applications like Atom, Slack, and Kitematic are built with Electron.

Call me old-fashioned, but I have always preferred using a desktop app suited to each purpose. I feel that if all I’m going to use is a browser for everything I do, then why have a ‘proper’ computer? On a practical level, I travel frequently and am generally ‘between’ internet connectivity or using unstable internet connections, and ‘real’ applications are typically far better at allowing effective offline working.

I appreciate how complex developing and maintaining native desktop applications is and can understand why companies push users towards web or cross-platform versions. There has been a plethora of options for accomplishing this over the decades. Flash, Air, Java and Sliverlight are all options that promised this capability with varying degrees of success.

The main problem with these options is that they generally involved learning another language (which defeats the point) or forced users to install plugins plagued with stability, performance and security problems.

We all know the power of JavaScript and web technologies and have seen a wave of options for developing and packaging cross-platform desktop apps using this knowledge.

Electron, by GitHub is one option, but as I already happily use several apps built with it, it seemed a good option to investigate. After two years of development, including one name change (from Atom shell), Electron has recently reached version 1.0, always a milestone in any project’s existence. What better time to see what it’s capable of.

Installing Electron

Electron has a quick start project and pre-built releases available, but let’s dive straight in the deep end and install Electron via npm:

<span>npm install electron-prebuilt -g
</span>
Copy after login
Copy after login
Copy after login

Or for Mac Homebrew lovers, via Cask:

<span>npm install electron-prebuilt -g
</span>
Copy after login
Copy after login
Copy after login

Whichever option you follow, you should end up with an executable electron binary.

Create Cross-Platform Desktop Node Apps with Electron

This application is only used for bundling and running your final project, not for creating one. For this you can use any standard text editor or IDE.

An Electron project requires three files:

  • index.html: The web page rendered by default.
  • main.js: Starts the app and creates a browser window to render HTML.
  • package.json: Lists the application dependencies, meta data and files needed.

Create Cross-Platform Desktop Node Apps with Electron

You Need a Hero

In this example I am going to create a simple application that connects to the Marvel API, pulls in 25 super heroes and displays their name and thumbnail image. It will display a system notification when the process is complete and have an OS-like application icon. An end-user will not be aware of how the application was created or be able to view the source code.

You can find the final project on GitHub.

Open package.json and add the following:

brew <span>install Caskroom/cask/electron
</span>
Copy after login
Copy after login

This is a standard package.json file and follows the same format and options as node.js. Here setting the application name, version, main JavaScript file and dependencies.

Run npm install after adding these to ensure you have the dependencies installed.

main.js handles interactions between the host operating system and your JavaScript code. This will be a simple example, you can find out more on what’s possible in Electron’s documentation.

First, let’s set up the requirements needed (i.e. electron), create an app, native browser window and a main window placeholder to work with.

<span>{
</span>  <span>"name": "hero-browser",
</span>  <span>"version": "0.1.0",
</span>  <span>"main": "main.js",
</span>  <span>"dependencies": {
</span>    <span>"dotenv": "^2.0.0",
</span>    <span>"md5": "^2.1.0"
</span>  <span>}
</span><span>}
</span>
Copy after login
Copy after login

Next handle quitting the application if windows are closed. If the platform is OS X, applications typically remain open after all windows are closed and users will normally explicitly quit, so handle that use case.

<span>'use strict';
</span>
<span>const electron = require('electron');
</span><span>const app = electron.app;  // Module to control application life.
</span><span>const BrowserWindow = electron.<span>BrowserWindow</span>;  // Module to create native browser window.
</span><span>var mainWindow = null;
</span>
Copy after login
Copy after login

Once Electron is initialized, create the browser window and load the application code. If the window is closed, dereference the window object.

app<span>.on('window-all-closed', function() {
</span>    <span>if (process.platform != 'darwin') {
</span>        app<span>.quit();
</span>    <span>}
</span><span>});
</span>
Copy after login
Copy after login

Create a subfolder called app. In app/index.html add references to the stylesheets and JavaScript files needed and setup the HTML structure of the interface.

app<span>.on('ready', function() {
</span>  mainWindow <span>= new BrowserWindow({width: 800, height: 600});
</span>  mainWindow<span>.loadURL('file://' + __dirname + '/app/index.html');
</span>
  mainWindow<span>.on('closed', function() {
</span>    mainWindow <span>= null;
</span>  <span>});
</span><span>});
</span>
Copy after login
Copy after login

Create app/css/index.css and add some basic css to aid layout.

<span><span><!DOCTYPE html></span>
</span><span><span><span><html</span>></span>
</span><span><span><span><head</span>></span>
</span>    <span><span><span><meta</span> charset<span>="UTF-8"</span>></span>
</span>    <span><span><span><title</span>></span>Marvel Super Hero Browser<span><span></title</span>></span>
</span>    <span><span><span><link</span> href<span>="css/index.css"</span> rel<span>="stylesheet"</span> type<span>="text/css"</span>/></span>
</span><span><span><span></head</span>></span>
</span><span><span><span><body</span>></span>
</span>    <span><span><span><h1</span>></span>Marvel Super Hero Browser<span><span></h1</span>></span>
</span>    <span><span><span><em</span>></span>Thanks to Marvel for their API.<span><span></em</span>></span>
</span>
    <span><span><span><div</span> id<span>="character_list"</span>></span><span><span></div</span>></span>
</span>
    <span><span><span><script</span> src<span>="js/index.js"</span>></span><span><span></script</span>></span>
</span><span><span><span></body</span>></span>
</span><span><span><span></html</span>></span>
</span>
Copy after login
Copy after login

Create app/js/index.js. This will be where most of the application functionality takes place. Start by setting up the dependencies and variables needed:

<span>npm install electron-prebuilt -g
</span>
Copy after login
Copy after login
Copy after login

The Marvel API is a fun API to use, but it’s authentication and data structure can be confusing. Sign up here for a key and follow these instructions to get the three parameters needed above. The public and private keys required for authentication are stored in a .env file and accessed using the dotenv package.

brew <span>install Caskroom/cask/electron
</span>
Copy after login
Copy after login

The limit value sets how many records to request and there are other parameters that can be set.

If you would rather skip connecting and authenticating with the Marvel API, then I created a JSON file of data for you to use instead. Replace the above JavaScript code with:

<span>{
</span>  <span>"name": "hero-browser",
</span>  <span>"version": "0.1.0",
</span>  <span>"main": "main.js",
</span>  <span>"dependencies": {
</span>    <span>"dotenv": "^2.0.0",
</span>    <span>"md5": "^2.1.0"
</span>  <span>}
</span><span>}
</span>
Copy after login
Copy after login

Next create the HTML and placeholder variables needed for outputting each character into the character_list div:

<span>'use strict';
</span>
<span>const electron = require('electron');
</span><span>const app = electron.app;  // Module to control application life.
</span><span>const BrowserWindow = electron.<span>BrowserWindow</span>;  // Module to create native browser window.
</span><span>var mainWindow = null;
</span>
Copy after login
Copy after login

Next, make a call to the API and process the response, drilling down into the JSON structure for the actual list of characters inside resp.data.results.

Create HTML elements for each character, appending them to character_list. Images in the Marvel API are separated into a file name and extension. If there is no image available, it displays a ‘no image available’ image, we could handle this, but won’t in this example.

When the loop completes, display a system notification, close methods and handle potential errors connecting to the API.

app<span>.on('window-all-closed', function() {
</span>    <span>if (process.platform != 'darwin') {
</span>        app<span>.quit();
</span>    <span>}
</span><span>});
</span>
Copy after login
Copy after login

Run the application by executing the command below in the project’s root directory:

app<span>.on('ready', function() {
</span>  mainWindow <span>= new BrowserWindow({width: 800, height: 600});
</span>  mainWindow<span>.loadURL('file://' + __dirname + '/app/index.html');
</span>
  mainWindow<span>.on('closed', function() {
</span>    mainWindow <span>= null;
</span>  <span>});
</span><span>});
</span>
Copy after login
Copy after login

Create Cross-Platform Desktop Node Apps with Electron

Packaging the Application

Packaging the code into a ‘native’ application is straightforward but requires a few pieces. First an icon for the application badge. The look and file type of this will depend on the operating systems you are targeting, but here’s the icon I used, taken from Marvel’s official Android app.

Create Cross-Platform Desktop Node Apps with Electron

Note: We are using copyrighted Marvel properties here for illustrative purposes. Please don’t distribute them as your own!

I then used iconverticons.com/online/ to convert the png to a Mac icon file, but there are other tools available.

The simplest way to package the project is by using the electron-packager npm module (Note: this needs to be installed separately). It can generate large binaries, for desktop apps this may not be an issue, but if it is, other options are described here.

If you are packaging for Windows on a non-Windows platform, you will need to install Wine, which is a large dependency.

Those caveats aside, here’s how to create the application binary. In your project folder, run (replacing with relevant values for your project):

<span><span><!DOCTYPE html></span>
</span><span><span><span><html</span>></span>
</span><span><span><span><head</span>></span>
</span>    <span><span><span><meta</span> charset<span>="UTF-8"</span>></span>
</span>    <span><span><span><title</span>></span>Marvel Super Hero Browser<span><span></title</span>></span>
</span>    <span><span><span><link</span> href<span>="css/index.css"</span> rel<span>="stylesheet"</span> type<span>="text/css"</span>/></span>
</span><span><span><span></head</span>></span>
</span><span><span><span><body</span>></span>
</span>    <span><span><span><h1</span>></span>Marvel Super Hero Browser<span><span></h1</span>></span>
</span>    <span><span><span><em</span>></span>Thanks to Marvel for their API.<span><span></em</span>></span>
</span>
    <span><span><span><div</span> id<span>="character_list"</span>></span><span><span></div</span>></span>
</span>
    <span><span><span><script</span> src<span>="js/index.js"</span>></span><span><span></script</span>></span>
</span><span><span><span></body</span>></span>
</span><span><span><span></html</span>></span>
</span>
Copy after login
Copy after login

In order, these parameters set:

  • The project folder.
  • The generated application name.
  • The platform: These are win32 for Windows, linux, darwin for vanilla Mac OS X and mas for a Mac App store release. Setting all, will generate a binary for all platforms.
  • The architecture: ia32 and x64 for 32 and 64 bit CPU architectures, or all.
  • The Electron Version to use.
  • The output binary location and wether to overwrite existing files.
  • The icons to use.

Note: All parameters can be comma separated for multiple values and if you want to generate all platforms and architectures you can replace the relevant parameters with --all.

Create Cross-Platform Desktop Node Apps with Electron

Further Steps

This was a simple example to illustrate the potential of Electron and much more is possible. Setting aside what can be accomplished with pure JavaScript, you might like to take a look at:

  • Mac App Store submissions.
  • Using Chrome Dev Tools.
  • Clipboard access.
  • Creating an application menu bar tool.
  • Electron’s new interactive API explorer.
  • Devtron, an extension to Chrome Dev Tools, specifically for Electron development.

Still skeptical? I’d like to point out that whilst writing this article in Atom, I communicated with the editor of this article in Slack and tested the application in Docker containers created in Kitematic. All of which are Electron generated applications. OK, they have their issues, but that’s pretty impressive!

I’d love to hear about the applications you build with Electron in the comments below.

Frequently Asked Questions about Desktop Node Apps with Electron

What are the prerequisites for developing desktop apps with Electron?

Before you start developing desktop applications with Electron, you need to have Node.js and npm (Node Package Manager) installed on your system. Node.js is a JavaScript runtime that allows you to run JavaScript on your server or your machine, while npm is a package manager for Node.js packages. You can download Node.js and npm from the official Node.js website. Once you have these installed, you can then install Electron using npm.

How do I install Electron on my system?

Installing Electron is quite straightforward. Once you have Node.js and npm installed, you can install Electron globally on your system using the following command in your terminal or command prompt: npm install -g electron. This command installs Electron globally, allowing you to access it from any directory on your system.

How do I create a new Electron project?

To create a new Electron project, first, create a new directory for your project. Navigate to this directory in your terminal or command prompt, and then initialize a new Node.js project using the command npm init. This command creates a new package.json file in your project directory. You can then install Electron in your project using the command npm install --save electron.

What is the structure of an Electron application?

An Electron application typically consists of three types of files: package.json, main.js, and index.html. The package.json file contains metadata about your application and its dependencies. The main.js file is the entry point of your application, where you can control your application’s life cycle events. The index.html file is the web page that is displayed when your application starts.

How do I run my Electron application?

To run your Electron application, navigate to your project directory in your terminal or command prompt, and then use the command electron .. This command starts your application.

How can I package my Electron application for distribution?

To package your Electron application for distribution, you can use a module like electron-packager or electron-builder. These modules allow you to package your application into an executable file that can be run on various platforms.

Can I use Node.js modules in my Electron application?

Yes, you can use Node.js modules in your Electron application. Electron uses Node.js runtime, so you can use any Node.js module in your application.

Can I use web technologies in my Electron application?

Yes, you can use web technologies in your Electron application. Electron is essentially a web browser that allows you to create desktop applications using web technologies like HTML, CSS, and JavaScript.

How can I debug my Electron application?

You can debug your Electron application using the Chrome Developer Tools. Electron is built on Chromium, so it includes a built-in developer tool that you can use to debug your application.

Can I build cross-platform applications with Electron?

Yes, you can build cross-platform applications with Electron. Electron allows you to build applications that run on Windows, macOS, and Linux.

The above is the detailed content of Create Cross-Platform Desktop Node Apps with Electron. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles