You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Electron渲染进程安全使用fs模块(无需开启nodeIntegration)

在Electron渲染进程安全使用fs模块(无需开启nodeIntegration)

要在不开启nodeIntegration: true和关闭contextIsolation: false的前提下实现渲染进程调用fs模块,核心是通过IPC通信让主进程处理文件操作,预加载脚本通过contextBridge向渲染进程暴露安全的调用接口。下面是具体修改步骤:

1. 修改主进程文件 main.js

调整窗口的webPreferences配置,开启上下文隔离、关闭node集成,同时添加IPC监听处理文件追加操作:

// Modules to control application life and create native browser window
const { app, BrowserWindow, ipcMain } = require('electron')
const path = require('path')
const fs = require('fs')

// Enable live reload for all the files inside your project directory
require('electron-reload')(__dirname);

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: false, // 关闭node集成
      contextIsolation: true, // 开启上下文隔离(默认就是true,显式声明更清晰)
      preload: path.join(__dirname, 'preload.js')
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// 监听渲染进程的文件追加请求
ipcMain.handle('append-file', async (event, filePath, content) => {
  return new Promise((resolve, reject) => {
    fs.appendFile(filePath, content, (err) => {
      if (err) reject(err)
      else resolve('文件追加成功')
    })
  })
})

app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

2. 创建/修改预加载脚本 preload.js

使用contextBridge向渲染进程暴露封装好的文件操作API,避免直接暴露IPC接口:

const { contextBridge, ipcRenderer } = require('electron')

// 向渲染进程暴露安全的API
contextBridge.exposeInMainWorld('electronAPI', {
  appendFile: (filePath, content) => ipcRenderer.invoke('append-file', filePath, content)
})

3. 修改渲染进程文件 renderer.js

移除直接require fs的代码,改用预加载脚本暴露的API:

document.onkeydown = async function(e) {
  switch (e.keyCode) {
    case 65:
      try {
        await window.electronAPI.appendFile('message.txt', 'data to append')
        console.log('file added')
      } catch (err) {
        console.error('文件追加失败:', err)
      }
      break;
    default:
      console.log("Key not found!");
  }
};

4. index.html 无需修改

原有的index.html保持不变即可,因为我们没有修改页面结构或引入新的脚本。

这样修改后,你的Electron应用就能在保证安全的前提下,实现渲染进程触发文件操作的需求,同时遵循Electron的安全最佳实践。

内容的提问来源于stack exchange,提问作者Anrisss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:23:28