Electron function to read a local file - FS - Not reading

后端 未结 2 2068
小蘑菇
小蘑菇 2020-12-14 04:50

I have an electron project when I need to get electron to read a local file.

Right now what I have is this, where it loads and displays the contents of a html file.<

相关标签:
2条回答
  • 2020-12-14 05:07

    Just one update information for the accepted answer. After the update of electron, you can directly use

    const { dialog } = require('electron');
    

    to import dialog.

    And for remote, if you need to use it, you also need:

    const { remote } = require('electron');
    
    0 讨论(0)
  • 2020-12-14 05:20

    Basically you need to do the following things.

    1.Loading required dependencies

    var remote = require('remote'); // Load remote compnent that contains the dialog dependency
    var dialog = remote.require('dialog'); // Load the dialogs component of the OS
    var fs = require('fs'); // Load the File System to execute our common tasks (CRUD)
    

    2.Read file content

    dialog.showOpenDialog((fileNames) => {
        // fileNames is an array that contains all the selected
        if(fileNames === undefined){
            console.log("No file selected");
            return;
        }
    
        fs.readFile(filepath, 'utf-8', (err, data) => {
            if(err){
                alert("An error ocurred reading the file :" + err.message);
                return;
            }
    
            // Change how to handle the file content
            console.log("The file content is : " + data);
        });
    });
    

    3.Update existing file content

     var filepath = "C:/Previous-filepath/existinfile.txt";// you need to save the filepath when you open the file to update without use the filechooser dialog againg
    var content = "This is the new content of the file";
    
    fs.writeFile(filepath, content, (err) => {
        if (err) {
            alert("An error ocurred updating the file" + err.message);
            console.log(err);
            return;
        }
    
        alert("The file has been succesfully saved");
    });
    

    For more read please visit here :) Thanks..

    One more thing to add..Please check that your path to file is correct. You could do something similar to below.

    var path = require('path');
    var p = path.join(__dirname, '.', 'README.md');
    
    0 讨论(0)
提交回复
热议问题