Reputation: 3
so I am using electron to build an app. I need to use "fs", but since I can't require it, because require doesn't work in electron, I'm stuck.
I already tried settings "nodeItegration: true" but it still won't work, also have I tried using a preload script but it still doesn't work. Maybe I have done something wrong with the preload script?
Code is below.
main.js
const electron = require("electron");
const url = require("url");
const path = require("path");
const {app, BrowserWindow} = electron;
let MainWindow;
app.on("ready", function(){
MainWindow = new BrowserWindow({
webPreferences: {
nodeIntergration: true,
preload: path.join(app.getAppPath(), 'preload.js')
}
});
MainWindow.loadURL(url.format({
pathname: path.join(__dirname, "index.html"),
protocol:"file:",
slashes: true
}));
});
console.log(require.resolve('electron'))
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>CommendBot UI</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<button class="safeData-button" onclick="safeData()">Safe</button>
</div>
</div>
<script>
// You can also require other files to run in this process
</script>
<script src="main.js"></script>
<script src="preload.js"></script>
</body>
</html>
preload.js
function safeData() {
var fs = require("fs");
var sampleObject = {
.......(some JSON data)
}
fs.writeFile("./object.json", JSON.stringify(sampleObject, null, 4), (err) => {
if (err) {
console.error(err);
return;
};
console.log("File has been created");
});
}
So whats basically not working, is my function call from my "Safe" button, which is calling the function to fs.writeFile and write a JSON file.
I am sorry for posting the whole code, not sure if it is more helpful or not.
Thanks for answers, in advance!
Upvotes: 0
Views: 201
Reputation: 12035
The problem is most likely a simple typo:
MainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true, // Note spelling!
preload: path.join(app.getAppPath(), 'preload.js')
}
});
Upvotes: 2