Desktop Operations in ElectronJS

Last Updated : 11 Jun, 2026

ElectronJ is an open-source framework for building cross-platform desktop applications with HTML, CSS, and JavaScript. It combines Chromium and Node.js into a single runtime, allowing apps to work across Windows, macOS, and Linux while still accessing native desktop capabilities through modules such as shell.

  • Supports desktop application development with familiar web technologies
  • Provides access to native operating system features through Electron modules
  • Includes the shell module for handling files, links, and shortcuts from the desktop environment

Project Structure:

Project Structure

sample.txt:

This is a Sample Text file

delete.txt:

Sample Text FIle to delete

Steps to Build an Electron Application 

Step 1: Create an empty project folder and open it in the terminal. Run:

npm init -y

This creates the package.json file.

Step 2: Install Electron as a development dependency:

npm install electron --save-dev

This creates the node_modules folder and package-lock.json file.

Step 3: Open package.json and set the main file and startup script correctly:

{
"name": "electron-desktop-operation",
"version": "1.0.0",
"description": "Desktop Operations in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"devDependencies": {
"electron": "^8.2.5"
}
}


Step 4: Create a file named main.js in the project root. This file starts the Electron app and creates the application window.

JavaScript
const { app, BrowserWindow } = require('electron')

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadFile('src/index.html')
  win.webContents.openDevTools()
}

app.whenReady().then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})


Step 5: Create a src folder, and inside it create index.html. This file is the application’s user interface.

HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <meta http-equiv="Content-Security-Policy"
          content="script-src 'self' 'unsafe-inline';" />
</head>
<body>
    <h1>Hello World!</h1>
    We are using node
    <script>
        document.write(process.versions.node)
    </script>, Chrome
    <script>
        document.write(process.versions.chrome)
    </script>, and Electron
    <script>
        document.write(process.versions.electron)
    </script>.
</body>
</html>

Start the Electron app with:

npm start

Output

Shell Module in Electron:

All the Shell modules are explained with the example below:

1. shell.openExternal(url, options):

To open External URLs in the systems default manner. We can pass external links or mail ID's and it will be resolved based on the protocol provided. 
The shell.OpenExternal(url, options) returns a Promise where,

  • url: String The external URL to be resolved. Maximum of 2081 Characters are allowed in Windows. URL will be resolved based on systems default behavior.
  • options: Object (Optional) It is an Object consisting of the following parameters, 
    • activate: Boolean It is supported by macOS only. It is used to bring the opened application to the foreground. Default is set as true.

index.html: Add the following snippet in that file.

HTML
<br> 
  <h3> 
   Desktop Integrations in Electron using Shell Module 
  </h3> 
  <button id="external"> 
   Open GeeksForGeeks.org in Default Browser 
  </button> 
  
  <br><br> 
  <button id="mail"> 
   Open GeeksForGeeks in Default Mail 
  </button> 


index.js: Add the following snippet in that file.

JavaScript
const electron = require('electron'); 
const path = require('path'); 
  
// Importing the Shell Module from the electron  
// in the Renderer Process 
const shell = electron.shell; 
  
var external = document.getElementById('external'); 
var externalOptions = { 
  
    // Supported by macOS only 
    activate: true, 
} 
  
external.addEventListener('click', (event) => { 
      
    // Returns a Promise<void>, Hence we can use  
    // the .then( function() {} ) 
    shell.openExternal( 
        'https://www.geeksforgeeks.org/', externalOptions) 
        .then(() => { 
            console.log('Link Opened Successfully'); 
        }); 
}); 
  
var mail = document.getElementById('mail'); 
  
mail.addEventListener('click', (event) => { 
  
    // Resolving the External URL to the Default Mail Agent 
    // Because we have specified 'mailto' 
    shell.openExternal( 
        'mailto: https://www.geeksforgeeks.org/', externalOptions) 
        .then(() => { 
        console.log('Link Opened Successfully'); 
    }); 
}); 

Output:

2. shell.showItemInFolder(path):

To resolve the given String file path and show the file in the Windows/File Explorer. If possible, select the file as well. This method does not have any return type. 

index.html: Add the following snippet in that file. 

HTML
<br><be>
  <button id="show">
    Show sample.txt in File Explorer
  </button>


index.js: Add the following snippet in that file. 

JavaScript
var show = document.getElementById('show');

show.addEventListener('click', (event) => {
    // Providing a dynamic file path to the 'sample.txt' 
    // file in the 'assets' Folder. Using the path Module. 
    // '__dirname' automatically detects current working directory
    shell.showItemInFolder(path.join(__dirname, '../assets/sample.txt'));
});

Output:

3. shell.openItem(path):

To resolve the given String file path and open the file in the systems default manner. It returns a Boolean value stating whether the file was successfully opened or not. 

index.html: Add the following snippet in that file. 

HTML
<br><br>
  <button id="open">Open sample.txt</button>


index.js: Add the following snippet in that file. 

JavaScript
var open = document.getElementById('open');

open.addEventListener('click', (event) => {
    var success = shell.openItem(path.join(__dirname, 
         '../assets/sample.txt'));

    console.log('File Opened Successfully - ', success);
});

Output:

4. shell.beep():

The shell.beep() method is used to play the system default beep sound. It does not take any parameters and does not return a value.

index.html: Add the following snippet in that file.

HTML
<br><br>
<button id="beep">
  Play System Beep
</button>


index.js: Add the following snippet in that file.

JavaScript
var beep = document.getElementById('beep');

beep.addEventListener('click', (event) => {
    shell.beep();
});

5. shell.moveItemToTrash(path, deleteFailure):

To resolve the given String file path and move the specified file to the Trash/Bin. Returns a Boolean value stating whether the file was successfully moved to the trash or not.

The shell.moveItemToTrash(path, delete) returns a Boolean value, where,

  • path: String The filepath to be resolved.
  • deleteFailure: Boolean (Optional) It is supported by macOS only. It signifies whether or not to remove the file entirely from the System in case the Trash is disabled or unsupported in the system.

index.html: Add the following snippet in that file.

HTML
<br><br> 
  <button id="delete">Delete delete.txt</button> 


index.js: Add the following snippet in that file.

JavaScript
var deleteItem = document.getElementById('delete'); 
  
deleteItem.addEventListener('click', (event) => { 
    // Play the Native OS Beep Sound 
    shell.beep(); 
      
    // Returns a Boolean Value 
    var success = shell.moveItemToTrash(path.join(__dirname,  
             '../assets/delete.txt'), true); 
  
    console.log('File Deleted Successfully - ', success); 
}); 

Output:

6. shell.writeShortcutLink(path, operation, options):

This operation is supported in Windows only. To resolve the given String path and create/update the Shortcut Link at that path. It returns a Boolean value stating whether the specified operation was successfully performed or not. 

The shell.writeShortcutLink(path, operations, options) returns a Boolean value, where,

  • path: String Defining the path for the shortcut for the Operation to be carried out.
  • operations: String (Optional) Specifies the Operation to be carried out. Default Value of the Operation is create. It can have any of the following values, 
    • create: Creates a new Shortcut. Performs Overwrite if necessary.
    • update: Updates the specified properties of an existing Shortcut.
    • replace: Overwrites an existing Shortcut. This operation fails if the Shortcut does not exist.
  • Options:
    • target: File or application launched by the shortcut.
    • args (Optional): Command-line arguments passed to the target.
    • description (Optional): Tooltip text displayed when hovering over the shortcut.
    • icon (Optional): Path to the shortcut icon (.exe or .dll file).
    • iconIndex (Optional): Icon resource ID used with icon.

index.html: Add the following snippet in that file.

HTML
<br><br> 
  <button id="create"> 
   Create sample.txt Shortcut 
  </button> 
<br><br> 


index.js: Add the following snippet in that file.

JavaScript
var create = document.getElementById('create'); 
  
var shortcutDetails = { 
    // Defining the target File as the 'sample.txt' File  
    target: path.join(__dirname, '../assets/sample.txt'), 
  
    // Current Working Directory is 'assets' folder 
    cwd: path.join(__dirname, '../assets/'), 
    args: "Passing Arguments", 
    // Shown as Tooltip  
    description: "Shortcut for sample.txt file", 
      
    // Defining the icon for shortcut as the  
    // 'notepad.exe' file  
    // Instead of the System Default icon 
    icon: "C://Windows//System32//notepad.exe",  
  
    // Keeping the default value of iconIndex for the  
    // 'notepad.exe' file icon to take effect   
    iconIndex: 0, 
    appUserModelId: "", 
} 
create.addEventListener('click', (event) => { 
  
    // Desktop - C:\\Users\\radhesh.khanna\\Desktop\\sample-shortcut.lnk 
    // Specifying the name of the Shortcut while creation 
    var success = shell.writeShortcutLink(path.join(__dirname,  
     '../assets/sample-shortcut.lnk'), 'create', shortcutDetails); 
  
    console.log('Shortcut Created Successfully - ', success); 
}); 

Output:

7. shell.readShortcutLink(path):

This method is supported only on Windows and is used to create or update a shortcut (.lnk) file. It returns a Boolean value indicating whether the operation was successful.

The shell.writeShortcutLink(path, operation, options) method, where:

  • path: Location of the shortcut file.
  • operation: Operation to perform (create, update, or replace).
  • options: Object containing shortcut properties such as target path, description, icon, and working directory.

index.html: Add the following snippet in that file. 

HTML
<div>
 <textarea name="Shortcut Details"
           id="textarea" cols="30" 
           rows="10">
 </textarea>
</div>

<button id="read">
   Read sample.txt Shortcut Details
</button>


index.js: Add the following snippet in that file. 

JavaScript
var read = document.getElementById('read');

// Defining a textarea to display the 'shortcutDetails' Object 
var textArea = document.getElementById('textarea');

read.addEventListener(('click'), (event) => {
    var object = shell.readShortcutLink(path.join(__dirname,
             '../assets/sample-shortcut.lnk'));

    // Object Returned is in JSON format, using 'JSON.stringify()' 
    // method to convert to String
    console.log(object);
    textArea.innerHTML = JSON.stringify(object);
});

Output:

Comment