[英]How to read a .txt file with ElectronJS?
我目前在嘗試使用 ElectronJS 讀取 a.txt 文件時遇到問題。
我已經使用電子快速啟動存儲庫(運行 Electron v8.2.1)開始測試,不知道它是否與它有關。
但讓我們開始吧。
我的索引.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>
我可以單擊該按鈕並單擊 select 中的 windows 文件,但我的控制台上沒有任何反應......按照本教程進行操作,並且它有效。 我究竟做錯了什么?
您應該在renderer.js
文件中編寫腳本,該文件作為<script src="./renderer.js"></script>
包含在正文的底部。 我對您的代碼進行了一些修改以使其正常工作:
nodeIntegration: true
在你的webPreferences
in main.js
renderer.js
文件將包含: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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.