Electron JS- Native capabilities

  •        0
  

We aggregate and tag open source projects. We have collections of more than one million projects. Check out the projects section.



Electron is an open source library to build native applications which also works as cross-platform desktop applications. It provision operating system functionalities with help of node integration. To know the licensing and basic of building simple electron app, please refer the article Desktop Apps using Electron JS.
 
In this article, we will go through how to access the Operating System variables, Inter system communication, System dialog, Access files, folders also their statistics.
 
Accessing System Variables and Information:
 
Electron's process is extended from the NodeJS process object. Process API will provide the native system process id, platform, argv, executable path, CPU usage and so on.
 
<script> 
//It prints the process version of chrome, node, electron installed 
   for (const type of ["chrome", "node", "electron"]) {
     console.log(process.versions as any)[type]);
   }
 //electron running process id
 console.log(process.pid);
 
 //Current running os
 console.log(process.platform);
 
 //arguments passed can be accessed in below variables
 console.log(process.argv);
 
 //environment variables showing system environment variables
 console.log(process.env);
 
 //prints current execution path
 console.log(process.execPath);
 
 //It prints cpu usage like { percentCPUUsage: 0, idleWakeupsPerSecond: 0 }
 console.log(process.getCPUUsage());
</script>

Inter Process Communication:
 
In Electron, there are two types of process, main and renderer. Main process are the node modules which loads the html file and Renderer process handles html UI related events.  Native functionalities are handled by the main process as it is node modules which has capability to interact with OS with C++ native programs. Renderer process as it is included inside html which is rendered in browser, this doesn't have OS capabilities.
 
So if we want to open the native folder dialog, by clicking on a button, it can send an event/message using ipcRenderer from the renderer process to main process through channel, In ipcMain, it listens on the channel and in return it will send the response in different channel using ipcMain.
 
Native File Functionalities:
 
Now in the renderer process, we send the event or message using ipcRenderer with channel named "showFolderDialog". renderer process
 
    btn.addEventListener("click", (ev: Event) => {
        ipcRenderer.send("showFolderDialog");
    });
 
 
In main process, ipcMain is listening to the channel which is sent from ipcRenderer. In this we open a electron dialog by giving properties like openFile, openDirectory which opens up the native folder dialog. This returns a promise which will get all the selected file path in the response obj.filepaths.
 
Now we can map the file path and read all the files inside the folder path using fs.readdirSync which accepts the file path and file type as true will get the dirent object. It will check the dirent object is not directory, so all files are filtered and passed to reduce function.
In reduce functions we combine all the files from all the paths and then get fs stats sync. Then send the stats and filename to renderer process.
 
main process
 
 ipcMain.on("showFolderDialog", (event: IpcMainEvent) => {

    let fileSelectionPromise = dialog.showOpenDialog({properties: ["openFile", "openDirectory", "multiSelections"]});
    fileSelectionPromise.then(function(obj) {
        //now for each folder path, get all the files inside it.. 
        let cumfileslist = obj.filePaths.map((filePath, index)=>{
          return fs.readdirSync(filePath, {withFileTypes: true})
                   .filter(dirent=>!dirent.isDirectory())
                   .map(dirent=>filePath + "/" + dirent.name);
        }).reduce((filesacc, files) => {
            filesacc = filesacc.concat(files);
            return filesacc;
        }).every((absolutefilepath, index, array) => {
          let stats:fs.Stats = fs.statSync(absolutefilepath);
          event.sender.send("fileslist", path.basename(absolutefilepath), stats);//sending back to renderer process
          return true;
        });
    });
  });
 
In renderer process, we will receive the file using ipcRenderer by listening to the channel and create DOM element to show in the html page. By this way, we can get the all files in the machine to display on html page.
 
renderer process
  
  ipcRenderer.on("selectedfolders", (evt: IpcRendererEvent, selectedfolders: string[]) => {
     const selectedFolderElem: HTMLInputElement = document.getElementById("selectedfolders") as HTMLInputElement;
     selectedFolderElem.value = selectedFolderElem.value !== "" ? selectedFolderElem.value + "|"
                                                            : selectedFolderElem.value ;
     selectedFolderElem.value += selectedfolders.join(" | ");
   });

Still there is option to have NodeJS capabilities in renderer process by having node integration as true. But doing this, will make the app vulnerable for security attacks when any external web pages are displayed in the desktop app. This has been more described in the electron apps site.
 

   

Nagappan is a techie-geek and a full-stack senior developer having 10+ years of experience in both front-end and back-end. He has experience on front-end web technologies like HTML, CSS, JAVASCRIPT, Angular and expert in Java and related frameworks like Spring, Struts, EJB and RESTEasy framework. He hold bachelors degree in computer science and he is very passionate in learning new technologies.

Subscribe to our newsletter.

We will send mail once in a week about latest updates on open source tools and technologies. subscribe our newsletter



Related Articles

Desktop Apps using Electron JS with centralized data control

  • electronjs couchdb pouchdb desktop-app

When there is a requirement for having local storage for the desktop application context and data needs to be synchronized to central database, we can think of Electron with PouchDB having CouchDB stack. Electron can be used for cross-platform desktop apps with pouch db as local storage. It can sync those data to centralized database CouchDB seamlessly so any point desktop apps can recover or persist the data. In this article, we will go through of creation of desktop apps with ElectronJS, PouchDB and show the sync happens seamlessly with remote CouchDB.

Read More


Best open source Text Editors

  • text-editor editor tools dev-tools

Text editors are mainly used by programmers and developers for manipulating plain text source code, editing configuration files or preparing documentation and even viewing error logs. Text editors is a piece of software which enables to create, modify and delete files that a programmer is using while creating website or mobile app.In this article, we will discuss about top 7 all-round performing text editors which is highly supportive for programmers.

Read More


Getting Started on Angular 7

  • angular ui-ux front-end-framework

Angular is a platform for building responsive web, native desktop and native mobile applications. Angular client applications are built using HTML, CSS and Typescript. Typescript is a typed superset of Javascript that compiles to plain Javascript. Angular core and optional modules are built using Typescript. Code has been licensed as MIT License.

Read More


Laravel eCommerce Platform - Bagisto

  • ecommerce shopping laravel php

Nowadays on the web, Shopping is one of the most popular activities. Everyone can shop at their recess, anytime from anywhere. However, this is interesting that anyone can have their pages built to display their favourite products and services.

Read More


Angular Service Workers Usage Guide

  • angular service-worker offline-app

Web developers come across scenarios like web application completely breaks when workstation goes offline. Likewise to get into our application, every time we need to open a browser and then access it. Instead if it is in app, it will be easy to access for end-user. Push notifications similar to email client need to be done through web application. All these are addressed by a magic called service worker.

Read More



ONLYOFFICE Document Server, an online office app for Nextcloud and ownCloud

  • office office-suite word spreadsheet

ONLYOFFICE Document Server is a free collaborative online office suite including viewers and editors for texts, spreadsheets and presentations, fully compatible with Office Open XML formats (.docx, .xlsx, .pptx). This article provides you the overview of ONLYOFFICE Document Server, its features, installation and integration with Nextcloud and ownCloud.

Read More


SeoToaster: easy, fast and efficient open source CMS for top SEO performance

  • cms content-management-system seo ecommerce

SeoToaster is a free Open Source CMS & Ecommerce solution to build, manage and market websites optimized for for top search engine performance. As the name implies, Seo Toaster is to date the only content management system (CMS) to truly integrate SEO execution and web marketing automation technology in full compliance with the search engines industry’s best practices.

Read More


Understanding Web Real-Time Communication (WebRTC)

  • webrtc communication web

Web Real-Time Communication (WebRTC) is an open source project currently being developed with an aim to provide real time, peer-to-peer communication between web applications. WebRTC provides simple JavaScript APIs that help developers to easily build web applications with real time audio, video and data transfer capabilities. This blog has been written assuming that the reader has zero knowledge of how WebRTC works and hence have explained the entire working in detail using simple terms and analogies wherever possible. Let’s get started!

Read More


COVID19 Stats using Angular Material Design

  • angular material-design covid covid-stats

Material design is inspired from the real world building architecture language. It is an adaptable system of guidelines, components, and tools that support the best practices of user interface design. Backed by open-source code, Material streamlines collaboration between designers and developers, and helps teams quickly build beautiful products. In this article, we will build COVID stats using Angular Material design.

Read More


Lucene / Solr as NoSQL database

  • lucene solr no-sql nosql document-store

Lucene and Solr are most popular and widely used search engine. It indexes the content and delivers the search result faster. It has all capabilities of NoSQL database. This article describes about its pros and cons.

Read More


Push Notifications using Angular

  • angular push-notifications notifications

Notifications is a message pushed to user's device passively. Browser supports notifications and push API that allows to send message asynchronously to the user. Messages are sent with the help of service workers, it runs as background tasks to receive and relay the messages to the desktop if the application is not opened. It uses web push protocol to register the server and send message to the application. Once user opt-in for the updates, it is effective way of re-engaging users with customized content.

Read More


Solr vs Elastic Search

  • full-text-search search-engine lucene solr elastic-search

Solr and Elastic Search are built on top of Lucene. Both are open source and both have extra features which makes programmer life easy. This article explains the difference and the best situation to choose between them.

Read More


New Open Source Web Browser Engine from Google and Mozilla

  • browser browser-engine

Web Browser engine used to render the page from HTML, CSS and Javascript. The browsers are one of the most important tool to view the web and it is must have software in Desktop and Mobile. These new browsers will take advantage of tomorrow’s faster, multi-core, heterogeneous computing desktop and mobile architectures.

Read More


Activiti - Open Source Business Automation

  • business-automation business bpm

Activiti Cloud is the first Cloud Native BPM framework built to provide a scalable and transparent solution for BPM implementations in cloud environments. The BPM discipline was created to provide a better understanding of how organisations do their work and how this work can be improved in an iterative fashion.

Read More


Introduction to Light 4J Microservices Framework

  • light4j microservice java programming framework

Light 4j is fast, lightweight, secure and cloud native microservices platform written in Java 8. It is based on pure HTTP server without Java EE platform. It is hosted by server UnderTow. Light-4j and related frameworks are released under the Apache 2.0 license.

Read More


Univention Corporate Server - An open source identity management system

  • ucs identity-management-system

Univention Corporate Server is an open source identity management system, an IT infrastructure and device management solution and an extensible platform with a store-like App Center that includes tested third party applications and further UCS components: This is what Univention combines in their main product Univention Corporate Server, a Debian GNU/Linux based enterprise distribution. This article provides you the overview of Univention Corporate Server, its feature and installation.

Read More


Exonum Blockchain Framework by the Bitfury Group

  • blockchain bitcoin hyperledger blockchain-framework

Exonum is an extensible open source blockchain framework for building private blockchains which offers outstanding performance, data security, as well as fault tolerance. The framework does not include any business logic, instead, you can develop and add the services that meet your specific needs. Exonum can be used to build various solutions from a document registry to a DevOps facilitation system.

Read More


Free Open Source Code Search Engines

  • code-search code-search-engine search-engine

There are couple of sites which indexes the open source code and provides support to search code. Recently Google announced that they removed code search support from Google code. This article provides pointer for code search engine sites.

Read More


Restrict Solr Admin Access

  • solr searchengine tips

Solr is a search engine built on top of Lucene. It supports REST interface and has lot of built-in capabilities. Solr package has Admin UI interface which has support to perform query and even delete the contents of the index. If you are using Solr in production then you may need to restrict access. I saw couple of questions in the group related to this topic. Thought to write an article explaining few tips to restrict the user access to Solr admin UI.

Read More


Why require Searchengine? Why not use database for full text search in Enterprise application.

  • searchengine database

Most of the database has support of full text search, basically indexing and saarching. MySQL, Oracle and many more databases has in-built full text search. Then what is the need to go for external search engine like Lucene, Sphinx, Solr etc. Check out the advantage of using Searchengine.

Read More