Node Fs Read Local File System From Electron

ElectronJS is an Open up 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.
There are several differences between a Drag-and-Driblet Performance in traditional web applications and Electron. I of the major differences is that Electron applications piece of work with the native filesystem in the OS environs. Hence we demand to obtain the absolute file path for any files dragged onto the Electron awarding from the native file dialog on the user'southward machine. Once nosotros have obtained the file path, we can perform file operations using the NodeJS fs module or upload the file to a server. Electron makes utilise of the HTML5 File API to work with files in the native filesystem. This tutorial will demonstrate how to implement Drag-and-Drib functionality for native files in an Electron application.
We presume that you lot 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.

  • Projection Structure:

Project Structure

Instance: We will showtime by building the basic Electron Application by post-obit the given steps.

  • Footstep 1: Navigate to an Empty Directory to setup the projection, and run the following control,
npm init
  • To generate the package.json file. Install Electron using npm if it is not installed.
npm install electron --save
  • This control will also create the package-lock.json file and install the required node_modules dependencies. Once Electron has been successfully installed, Open the package.json file and perform the necessary changes under the scripts key. Create the assets folder according to the project construction. Re-create any Epitome file of your choosing into the assets folder and proper noun it equally image.png. In this tutorial, we will exist using the Electron logo as the image.png file. This image file will exist dragged-and-dropped onto the BrowserWindow of the Electron application.
    bundle.json:
{   "proper name": "electron-drag",   "version": "1.0.0",   "clarification": "File Drag and Drop in Electron",   "main": "main.js",   "scripts": {     "start": "electron ."   },   "keywords": [     "electron"   ],   "author": "Radhesh Khanna",   "license": "ISC",   "dependencies": {     "electron": "^8.three.0"   } }
  • Footstep 2: Create a master.js file co-ordinate to the project construction. This file is the Primary Process and acts every bit an entry point into the application. Copy the Boilerplate lawmaking for the main.js file every bit given in the following link. We have modified the code to suit our project needs.
    primary.js:

javascript

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

role createWindow () {

const win = new BrowserWindow({

width: 800,

summit: 600,

webPreferences: {

nodeIntegration: true

}

})

win.loadFile( 'src/alphabetize.html' )

win.webContents.openDevTools()

}

app.whenReady().and then(createWindow)

app.on( 'window-all-closed' , () => {

if (procedure.platform !== 'darwin' ) {

app.quit()

}

})

app.on( 'activate' , () => {

if (BrowserWindow.getAllWindows().length === 0) {

createWindow()

}

})

  • Step three: Create the index.html file and alphabetize.js file inside the src directory according to project structure. Nosotros volition also re-create the Boilerplate lawmaking for the index.html file from the above-mentioned link. We have modified the code to arrange our projection needs.
    index.html:

html

<!DOCTYPE html>

< html >

< head >

< meta charset="UTF-8">

< championship >How-do-you-do World!</ title >

< meta http-equiv="Content-Security-Policy"

content="script-src 'self' 'dangerous-inline';" />

</ head >

< torso >

< h1 >Hello World!</ h1 >

Nosotros 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 >

< h3 >Drag and Drib Files in the Window.</ h3 >

< script src="alphabetize.js"></ script >

</ body >

</ html >

  • Output: At this betoken, our basic Electron Application is set up. To launch the Electron Awarding, run the Control:
npm start

GUI Output

Using the HTML5 File API, users tin directly work with the native files in the system Bone environment. This is possible because the DOM's File Interface provides an brainchild for the underlying native filesystem. Electron enhances the DOM's File Interface by adding a path attribute to information technology. This path attribute exposes the absolute file path of the files on the filesystem. We will exist making use of this functionality to become the absolute file path of a dragged-and-dropped file onto the Electron application. For more detailed Information, Refer this link.
All the Instance events of the Drag-and-Drop Functioning belong to the DragEvent Interface. This effect is a DOM Effect that represents a elevate-and-drib operation from commencement to finish. This Interface as well inherits properties from the MouseEvent and the global Issue Interface. It has specific Instance Backdrop for information transfer, GlobalEventHandlers and Instance Events which we take used in our code. For more detailed Data, Refer this link.
index.js: Add together the post-obit snippet in that file.

javascript

document.addEventListener( 'driblet' , (event) => {

outcome.preventDefault();

event.stopPropagation();

for (const f of event.dataTransfer.files) {

panel.log( 'File Path of dragged files: ' , f.path)

}

});

document.addEventListener( 'dragover' , (e) => {

e.preventDefault();

e.stopPropagation();

});

certificate.addEventListener( 'dragenter' , (issue) => {

console.log( 'File is in the Driblet Space' );

});

document.addEventListener( 'dragleave' , (effect) => {

console.log( 'File has left the Drop Infinite' );

});

A Detailed caption of all the Example Events and Backdrop of the HTML5 File API used in the code are explained below. All the Instance Events of DragEvent Interface will be fired upon the global document object and cannot be directly fired on a Specific DOM element.

  • event.dataTransfer This Instance Holding is used to correspond the information that is being transferred during a Drag and Drop Functioning. In our case, the data being transferred is a file and hence we take used event.dataTransfer.files and fetched the accented file path using the path attribute provided by Electron. We tin also drag and drop multiple files at once. In example of the information beingness a text selection, nosotros can simply use issue.dataTransfer.setData(central, text) method when initiating a Elevate operation. This method sets a unique fundamental for the text data being transferred. To recollect the text selection on the Drop Operation, we tin can simply apply result.dataTransfer.getData(key) method. This method will render whatsoever data which was ready using the unique key provided.
  • dragover: Effect This event is fired when an element or text option is being dragged over a valid driblet target (every few hundred milliseconds) such equally another DOM element. The firing pattern for this event depends on the movement of the mouse arrow. By default, this event fires every 50 ms when the mouse pointer is not moving over a valid drop target else much faster between 5 ms and ane ms approximately but this behaviour varies. The Consequence Handler Property for this consequence is ondragover. Past default, a element or a text selection cannot be dropped in other DOM elements. To allow a driblet, we must preclude the default handling of the element. Hence we have used the event.preventDefault() method for this very purpose. The default handling of an element is open every bit link in the browser on drop.
  • drop: Consequence This upshot is fired when an element or text selection is dropped on a valid drop target such every bit another DOM chemical element. The Consequence Handler Property for this upshot is ondrop. We need to prevent the default handling of the chemical element in this Event also as done for the dragover Event.
  • dragenter: Event This event is fired when a dragged element or text selection enters a valid drib target such as another DOM element. The Event Handler Property for this upshot is ondrageneter.
  • dragleave: Event This event is fired when a dragged element or text selection leaves a valid drop target such as another DOM element. The Event Handler Holding for this event is ondragleave.

The dragStart, drag, dragend and dragexit Case events will non be fired in this particular lawmaking example and hence have been excluded from the aforementioned. All of these Instance Events are fired on the Elevate Target and in this case, drag Target does not be in the application. The Drag Operation for files is initiated from outside the application from inside the native filesystem dialog. All of the Instance events used in the above code are triggered on the Driblet Target which lies within the application.
Notation: The event.stopPropagation() method prevents propagation of the same issue from being chosen. Propagation ways transferring up to the Parent DOM elements or transferring down to the Kid DOM elements.
Output:


navawhings.blogspot.com

Source: https://www.geeksforgeeks.org/drag-and-drop-files-in-electronjs/

0 Response to "Node Fs Read Local File System From Electron"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel