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.
I just need it to read a file and store it on a variable for now.
Here is my current main.js:
JavaScript
x
46
46
1
const {app, BrowserWindow } = require('electron');
2
const path = require('path');
3
const url = require('url');
4
var fs = require('fs');
5
6
let mainWindow;
7
8
function createNewWindow() {
9
mainWindow = new BrowserWindow({
10
width: 1300,
11
height: 1000,
12
minWidth: 600,
13
minHeight: 400,
14
title: 'Test App'
15
})
16
}
17
18
function loadInitialUrl() {
19
mainWindow.loadURL(url.format({
20
pathname: path.join(__dirname, 'index.html'),
21
protocol: 'file:',
22
slashes: true
23
}))
24
}
25
26
function closeApplication() {
27
mainWindow.on('closed', () => {
28
mainWindow = null;
29
})
30
}
31
32
33
app.on('ready', function(){
34
createNewWindow();
35
loadInitialUrl();
36
mainWindow.setMenu(null);
37
mainWindow.openDevTools();
38
fs.readFile('./README.md', 'utf8', function (err,data) {
39
if (err) {
40
return console.log(err);
41
}
42
console.log(data);
43
});
44
mainWindow.on('closed', function() {mainWindow = null;});
45
});
46
How can I do this as it’s not showing the contents of the README.md file in the console.log
Advertisement
Answer
Basically you need to do the following things.
1.Loading required dependencies
JavaScript
1
4
1
var remote = require('remote'); // Load remote compnent that contains the dialog dependency
2
var dialog = remote.require('dialog'); // Load the dialogs component of the OS
3
var fs = require('fs'); // Load the File System to execute our common tasks (CRUD)
4
2.Read file content
JavaScript
1
18
18
1
dialog.showOpenDialog((fileNames) => {
2
// fileNames is an array that contains all the selected
3
if(fileNames === undefined){
4
console.log("No file selected");
5
return;
6
}
7
8
fs.readFile(filepath, 'utf-8', (err, data) => {
9
if(err){
10
alert("An error ocurred reading the file :" + err.message);
11
return;
12
}
13
14
// Change how to handle the file content
15
console.log("The file content is : " + data);
16
});
17
});
18
3.Update existing file content
JavaScript
1
13
13
1
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
2
var content = "This is the new content of the file";
3
4
fs.writeFile(filepath, content, (err) => {
5
if (err) {
6
alert("An error ocurred updating the file" + err.message);
7
console.log(err);
8
return;
9
}
10
11
alert("The file has been succesfully saved");
12
});
13
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.
JavaScript
1
3
1
var path = require('path');
2
var p = path.join(__dirname, '.', 'README.md');
3