简体   繁体   中英

How to read a .txt file with ElectronJS?

I'm currently with problems while trying to read a.txt file with ElectronJS.

I've start the test using the electron-quick-start repository (running Electron v8.2.1), don't know if it's something with it.

But let's get into it.

my index.html:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
  <title>Hello World!</title>
</head>

<body>
  <input type="button" id="btn-readfile" value="Select a file">

  <script>
    const fs = require('fs')
    const {
      dialog
    } = require('electron').remote

    document.getElementById('btn-readfile').addEventListener('click', () => {
      dialog.showOpenDialog((fileNames) => {
        if (fileNames === undefined) {
          console.log("No files were selected")
          return
        }

        fs.readFile(fileNames[0], 'utf-8', (err, data) => {
          if (err) {
            return
          }

          console.log("The content is: ")
          console.log(data)
        })
      })
    }, false)
  </script>
</body>

</html>

I'm able to click the button and select the file from the windows, but nothing happens on my console... Followed this tutorial, and It works. What am I doing wrong?

You should be writing your script inside the renderer.js file which is included in the bottom of the body as <script src="./renderer.js"></script> . I did some modifications to your code in order to make it work:

  1. Make sure this nodeIntegration: true is in your webPreferences in main.js
  2. Your renderer.js file would then contain:
const fs = require('fs')
const {dialog} = require('electron').remote

document.getElementById('btn-readfile').addEventListener('click', () => {
     dialog.showOpenDialog({
          properties: ['openFile']
       }).then((data) => {
            console.log(data)
               if(data){
                    fs.readFile( data.filePaths[0], 'utf-8', (err, data) => {
                         if (err)
                              return
                         console.log("The content is: ")
                         console.log(data)
                    })
               }
       });
}, false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM