Access the terminal in your Electron/Angular application.

Discover the world of IT

Access the terminal in your Electron/Angular application.

When creating an desktop application using Electron there might be situations where you need to call systems functions.

I have just experienced this while working on a custom git client, and found a easy way to access the terminal as the electron application is allowed to carry out these tasks.

In the index.ts found in your electron application you are able to make an event listener which can be triggered and make a callback from an angular application.

In the electron application this can be handled by setting up and receiver and a sender.

I have for my project created a terminal initialization listner that are called while building the electron app, allowing the electron app to rechive a command string execute it and send back a response.

function initTerminalListener(){
  ipcMain.on('exec', (event: IpcMessageEvent, arg: string) => {
    exec(arg, (err: Error, stdout: string | Buffer, stderr: string | Buffer) => {
      event.sender.send('execRes', {Error: err, stdOut: stdout, stdErr: stderr});

By defining a type of the response like the terminal type seen below, allows for an easier readable when the response is returned from the electron app, and can be used in the angular application to determine if the command failed or went successfully.

type Terminal = {
  Error: Error, 
  stdOut: string |Buffer, 
  stdErr: string |Buffer

The following code can be used anywhere in angular application and executes and ipconfig which on Windows will show a list of IP addresses. however this will be shown in the Angular application console rather than the terminal that executed the application (the OS specific terminal).

import { ipcRenderer } from 'electron';
ipcRenderer.on('execRes', (event: Electron.IpcMessageEvent, arg: Terminal) => {

ipcRenderer.send('exec', 'ipconfig');

This sets the listener on the response, so that we are ready to receive the response in the angular application before the ipconfig command is send to the electron application executed and printed. This is made possible using the ipcRenderer which has to be imported whereever the code is implemented.

Hope this helps with easier accessing the system resources in your ElectronJS applications.

Leave a Reply

Your email address will not be published. Required fields are marked *