electron中调用node.js API

发布时间 2023-06-25 16:51:32作者: 妄欢

主进程在node.js环境中运行,等同于它拥有调用require模块和使用所有node.jsAPI的能力。但是在渲染器进程中,渲染器是无法直接访问require和其他node.jsAPI的,想要访问有以下两种方法:

Preload脚本

预加载脚本运行在渲染器环境中,可以在BrowserWindow构造方法中的webPreferences选项里被附加到主进程main.js:

const { BrowserWindow } = require('electron')
// ...
const win = new BrowserWindow({
  webPreferences: {
    preload: 'path/to/preload.js' // 在此引入对应的预加载脚本
  }
})
// ...
preload.js
const fs = require('fs');
fs.readFile('文件名', (err, data) => {
  xxxxxxxxxxxxx
})

2.想要在渲染进程中引入的js文件中调用node.js模块,可以在BrowserWindow中进行以下配置

const secondWindow=new BrowserWindow({
        width:400,
        height:200,
        parent:mainWindow,
        webPreferences:{
            nodeIntegration:true,   //允许渲染进程使用node.js
            contextIsolation:false  //允许渲染进程使用node.js
        }
    })

 例如引入tool.js

const fs=require('fs')
fs.readFile('package.json',(err,data)=>{
    if(err){
        console.log(err)
        return
    }
    console.log('render.js')
    console.log(data.toString())
})