所以我正在使用电子来构建应用程序。我需要使用“ fs”,但是由于不需要,因为require在电子中不起作用,所以我被卡住了。
我已经尝试过设置“ nodeItegration:true”,但仍然无法使用,也尝试过使用预加载脚本,但是仍然无法使用。也许我的预加载脚本做错了什么?
下面是代码。
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");
});
}
所以基本上从我的“安全”按钮调用函数是不起作用的,该按钮正在调用fs.writeFile函数并写入JSON文件。
对不起,我发布了整个代码,不确定它是否更有帮助。
提前感谢您的回答!
问题很可能是一个简单的错字:
MainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true, // Note spelling!
preload: path.join(app.getAppPath(), 'preload.js')
}
});