javascriptfilemethodsioelectron

How to read a local file in Javascript (Running from an Electron App)


I have been searching for over an hour or so, and I cant find an answer to my question. Is there a way to get the text from a local file, using just a plain old file URL?

I have found numerous ways to read a file via file input HTML tag, but I have had an incredible pain, finding a code example that can find a file, on my PC, using just plain old JS.

The code will be inside an electron application.

I need code examples. Something like this:

readFile("file:\\\\C:\path\to\file.txt","text/plain");

readFile(url,mimetype){
 ....
}

Solution

    1. Reading a file is done using node and is not dependent on electron
    2. Where you have the code for creating a window add this code
    const fs = require("fs");
    
    function readFile(fileURL,mimeType){
       //readfile does not accept the file:\\\ thing, so we remove it
       const pathToFile = fileURL.replace("file:\\\\",'');
    
       fs.readFile(pathToFile,mimeType,(err,contents)=>{
         if(err){
            console.log(err);
            return;
         }
         console.log(contents);
       })
    }
    
    readFile('C:\\Users\\<userAccount>\\Documents\\test.txt','utf8')
    //If your on windows you'll need to use double backslashes for the paths
    //here's an example regex to do that
    
    pathToFile = pathToFile.replace(/\\/,'\\\\')