ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.
Any native desktop application should integrate itself with the System OS environment. The application should have the ability to interact with core OS functionalities such as the File System, System Tray, etc. Electron provides us with built-in dialog module to display the native System dialogs for interacting with files. This tutorial will use the instance method of the dialog module to demonstrate how to Save Files locally in Electron.
We assume you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.
dialog Module: The dialog Module is part of the Main Process. To import and use the dialog Module in the Renderer Process, we will be using Electron remote module. For more details on the remote module, Refer this link.
- Project Structure:

Example: We will start by building the Electron Application for Saving files to local System by following the given steps.
- Step 1: Navigate to an Empty Directory to setup the project, and run the following command.
npm init
To generate the package.json file. Install Electron using npm if it is not installed.
npm install electron --save
This command will also create the package-lock.json file and install the required node_modules dependencies. Create the assets folder according to the project structure. We will save the new files to this folder from the native dialog.
package.json:
{
"name": "electron-save",
"version": "1.0.0",
"description": "Save Files to local in Electron",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"keywords": [
"electron"
],
"author": "Radhesh Khanna",
"license": "ISC",
"dependencies": {
"electron": "^8.2.5"
}
}
- Step 2: Create the main.js file according to the project structure. This file is the Main Process and acts as an entry point into the application. Copy the Boilerplate code for the main.js file as given in the following link. We have modified the code to suit our project needs.
main.js:
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 3: Create the index.html file and index.js file within the src directory. We will also copy the boilerplate code for the index.html file from the above-mentioned link. We have modified the code to suit our project needs.
index.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 >.
< br >< br >
< button id = "save" >Save sample.txt to local System</ button >
< script src = "index.js" ></ script >
</ body >
</ html >
|
Output: At this point, our application is set up and we can launch the application to check the GUI Output. To launch the Electron Application, run the Command:
npm start

- Step 4: The Save sample.txt to local System button does not have any functionality associated with it yet.
index.js: Add the following snippet in that file.
const electron = require( 'electron' );
const path = require( 'path' );
const fs = require( 'fs' );
const dialog = electron.remote.dialog;
var save = document.getElementById( 'save' );
save.addEventListener( 'click' , (event) => {
dialog.showSaveDialog({
title: 'Select the File Path to save' ,
defaultPath: path.join(__dirname, '../assets/sample.txt' ),
buttonLabel: 'Save' ,
filters: [
{
name: 'Text Files' ,
extensions: [ 'txt' , 'docx' ]
}, ],
properties: []
}).then(file => {
console.log(file.canceled);
if (!file.canceled) {
console.log(file.filePath.toString());
fs.writeFile(file.filePath.toString(),
'This is a Sample File' , function (err) {
if (err) throw err;
console.log( 'Saved!' );
});
}
}). catch (err => {
console.log(err)
});
});
|
The dialog.showSaveDialog(browserWindow, options) takes in the following parameters. For more detailed information on dialog.showSaveDialog() method, Refer this link.
- browserWindow: BrowserWindow (Optional) The BrowserWindow Instance. This argument allows the native dialog to attach itself to the parent window, making it a modal. A modal window is a child window that disables the parent window. If BrowserWindow Instance is not shown, dialog will not be attached to it. In such case It will be displayed as independent window. In the above code, the BrowserWindow instance is not being passed to the dialog, therefore the dialog opens as an independent window on clicking the Save sample.txt to local System button. For more detailed information on BrowserWindow Object and Modal window, Refer this link.
- options: Object It takes in the following parameters,
The dialog.showSaveDialog(browserWindow, options) returns a Promise. It resolves to an Object containing the following parameters,
- canceled: Boolean Whether or not the dialog operation was cancelled.
- filePath: String (Optional) The file path chosen by the user. If the dialog operation is cancelled, it is going to be undefined.
- bookmark: String (Optional) This return String is supported in macOS only. It is a Base64 encoded String which contains the security scoped bookmark data for the saved file. This is returned when the securityScopedBookmarks parameter is defined as true in the options Object. For the different return values, Refer this link.
The fs.writeFile(file, data, options, callback) method is used to write the specified data to a file. By default, this will replace the file if it exists at the defined file path. We have specified the absolute file path, the String data to be written and a callback for handling Error in the above code. We can use the options parameter to modify the functionality. For more detailed Information, Refer this link.
We should now be able to successfully choose the file path from the dialog window, give a new file name (if required, in our code will be sample.txt by default) and save the newly created sample.txt file at that path.
Output:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Aug, 2022
Like Article
Save Article