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>
Or for Mac Homebrew lovers, via Cask:
<span>npm install electron-prebuilt -g </span>
Whichever option you follow, you should end up with an executable electron binary.
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.
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>
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>
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>
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>
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>
Create app/css/index.css and add some basic css to aid layout.
<span><span> </span><span><span><span>></span> </span><span><span><span>></span> </span> <span><span><span><meta> charset<span>="UTF-8"</span>></span> </span> <span><span><span><title>></title></span>Marvel Super Hero Browser<span><span></span>></span> </span> <span><span><span><link> href<span>="css/index.css"</span> rel<span>="stylesheet"</span> type<span>="text/css"</span>/></span> </span><span><span><span></span>></span> </span><span><span><span>></span> </span> <span><span><span><h1 id="gt">></h1></span>Marvel Super Hero Browser<span><span></span>></span> </span> <span><span><span><em>></em></span>Thanks to Marvel for their API.<span><span></span>></span> </span> <span><span><span><div> id<span>="character_list"</span>><span><span></span></span> </div></span>></span> </span> <span><span><span><script> src<span >="js/index.js"</script></span>></span><span><span></span>></span> </span><span><span><span></span>></span> </span><span><span><span></span>></span> </span></span></span></span></span></span></span></span></span></span>
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>
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>
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>
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>
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>
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>
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.
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> </span><span><span><span>></span> </span><span><span><span>></span> </span> <span><span><span><meta> charset<span>="UTF-8"</span>></span> </span> <span><span><span><title>></title></span>Marvel Super Hero Browser<span><span></span>></span> </span> <span><span><span><link> href<span>="css/index.css"</span> rel<span>="stylesheet"</span> type<span>="text/css"</span>/></span> </span><span><span><span></span>></span> </span><span><span><span>></span> </span> <span><span><span><h1 id="gt">></h1></span>Marvel Super Hero Browser<span><span></span>></span> </span> <span><span><span><em>></em></span>Thanks to Marvel for their API.<span><span></span>></span> </span> <span><span><span><div> id<span>="character_list"</span>><span><span></span></span> </div></span>></span> </span> <span><span><span><script> src<span >="js/index.js"</script></span>></span><span><span></span>></span> </span><span><span><span></span>></span> </span><span><span><span></span>></span> </span></span></span></span></span></span></span></span></span></span>
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.
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!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)