Search code examples
javascriptfilemethodsioelectron

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


How can I read the text from a local file using a plain file URL in JavaScript?

I’ve found plenty of examples for reading files via the HTML file input tag, but I’m struggling to find a straightforward example of accessing a file on my PC using plain JavaScript. This will be for an Electron application.

I need a code example, such as:

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

readFile(url, mimetype) {
    // Implementation here
}

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(/\\/,'\\\\')