Reputation: 23
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?
Upvotes: 2
Views: 834
Reputation: 28414
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:
nodeIntegration: true
is in your webPreferences
in main.js
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);
Upvotes: 1