Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Electron Hands-on Projects

Electron Hands-on Projects

Through hands-on projects, you can deepen your understanding of various Electron features, including window management, IPC communication, file operations, data storage, and UI optimization.


Project 1: Desktop note application

Feature design

Tech stack choices

Implementation Steps

1. Create an Electron project

mkdir electron-notes

cd electron-notes

npm init -y

npm install electron electron-store

2. Main process main.js

Example

const

{

app

,

BrowserWindow

,

ipcMain

}

=

require

(

'electron'

)

const

Store

=

require

(

'electron-store'

)

const

store

=

new

Store

(

)

let mainWindow

app.

whenReady

(

)

.

then

(

(

)

=>

{

  mainWindow

=

new

BrowserWindow

(

{

    width

:

800

,

    height

:

600

,

    webPreferences

:

{

      preload

:

`$

{

__dirname

}

/

preload.

js

`

   

}

 

}

)

  mainWindow.

loadFile

(

'index.html'

)

}

)

// IPC: Read notes

ipcMain.

handle

(

'get-notes'

,

(

)

=>

store.

get

(

'notes'

,

[

]

)

)

// IPC: Save notes

ipcMain.

handle

(

'save-notes'

,

(

event

,

notes

)

=>

store.

set

(

'notes'

,

notes

)

)

3. Preload script preload.js

Example

const

{

contextBridge

,

ipcRenderer

}

=

require

(

'electron'

)

contextBridge.

exposeInMainWorld

(

'api'

,

{

  getNotes

:

(

)

=>

ipcRenderer.

invoke

(

'get-notes'

)

,

  saveNotes

:

(

notes

)

=>

ipcRenderer.

invoke

(

'save-notes'

,

notes

)

}

)

4. Renderer process index.html

Example

 

   

   

   

 

Code Analysis


Project 2: File manager

Interface design

File operation implementation

Example

// Main process main.js

const

fs

=

require

(

'fs'

)

const

path

=

require

(

'path'

)

ipcMain.

handle

(

'read-dir'

,

(

event

,

dirPath

)

=>

fs.

readdirSync

(

dirPath

)

)

ipcMain.

handle

(

'create-file'

,

(

event

,

filePath

)

=>

fs.

writeFileSync

(

filePath

,

''

)

)

ipcMain.

handle

(

'delete-file'

,

(

event

,

filePath

)

=>

fs.

unlinkSync

(

filePath

)

)

Example

// Renderer process

window.

api

.

readDir

(

'/Users/username/Documents'

)

.

then

(

files

=>

{

  console.

log

(

files

)

}

)

Drag-and-drop functionality

Example

// Renderer process drop event

const

dropArea

=

document.

getElementById

(

'fileList'

)

dropArea.

addEventListener

(

'drop'

,

(

event

)

=>

{

  event.

preventDefault

(

)

 

const

filePath

=

event.

dataTransfer

.

files

[

0

]

.

path

  window.

api

.

moveFile

(

filePath

,

targetDir

)

}

)

Performance optimization


Summary

Through these two hands-on projects, you can master:

These projects can serve as base templates for later complex desktop application development, helping to quickly build fully featured Electron apps.