文件读取和保存
-
html
<button onclick="openFile()">打开文件</button> <textarea name="" id="" cols="30" rows="10"></textarea> <button onclick="saveFile()">保存文件</button>
-
index.js
const {remote: {dialog}} = require('electron') const fs = require('fs') //打开文件 const textareaEl = document.querySelector('textarea') const openFile = function () { const res = dialog.showOpenDialogSync({ title: '读取文件', buttonLabel: '读取', filters: [ { // 只读取js文件 name: 'Custom File Type', extensions: ['js'] } ] }) const fileContent = fs.readFileSync(res[0]).toString() textareaEl.value = fileContent } // 保存文件 const saveFile = function () { const res = dialog.showSaveDialogSync({ title: '保存文件', buttonLabel: '保存', filters: [ { // 只读取js文件 name: 'index', extensions: ['js'] } ] }) fs.writeFileSync(res, textareaEl.value) }