Electron应用从CommonJS转ES模块后无法访问XLSX文件
Electron ES模块下xlsx.readFile无法访问含空格路径文件的解决方案
问题背景
我在Electron开发的桌面应用中读取XLSX文件,CommonJS模式下代码可正常运行,但转为ES模块后,调用xlsx.readFile时抛出Error: Cannot access file错误——尽管输出的文件路径完全正确,且路径和文件名包含空格无法移除。
CommonJS正常代码:
const path = require('node:path'); const xlsx = require('xlsx'); const dirPath = __dirname; const filename = "ExampleXLSX.xlsx"; const workbook = xlsx.readFile(path.join(dirPath, filename)); if (workbook !== 'undefined') { console.log("Success") }
转为ES模块后的报错代码:
import { dirname, join } from 'node:path'; import { fileURLToPath } from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); import * as xlsx from 'xlsx'; const dirPath = __dirname; const filename = "ExampleXLSX.xlsx"; const workbook = xlsx.readFile(join(dirPath, filename)); if (workbook !== 'undefined') { console.log("Success") }
解决方案
方案1:通过fs读取文件Buffer后解析
绕过xlsx.readFile的路径处理逻辑,先用Node.js的fs模块读取文件为Buffer,再交给xlsx解析:
import { dirname, join } from 'node:path'; import { fileURLToPath } from 'url'; import * as xlsx from 'xlsx'; import { readFileSync } from 'node:fs'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const filePath = join(__dirname, "ExampleXLSX.xlsx"); // 读取文件为Buffer const fileBuffer = readFileSync(filePath); // 解析Buffer生成workbook const workbook = xlsx.read(fileBuffer); if (workbook) { console.log("Success"); }
方案2:验证路径一致性
打印ES模块下生成的路径,对比CommonJS模式下的路径输出,确认两者完全一致:
// ES模块中添加打印 const filePath = join(__dirname, "ExampleXLSX.xlsx"); console.log('ES模块路径:', filePath); // CommonJS中添加打印 const filePathCJS = path.join(__dirname, filename); console.log('CommonJS路径:', filePathCJS);
若路径存在差异,检查import.meta.url的处理是否正确,比如是否在Electron的主/渲染进程中有不同的路径解析逻辑。
方案3:确认Electron ES模块配置
确保项目根目录的package.json已设置:
{ "type": "module" }
如果是主进程代码,需确认Electron启动时支持ES模块(Electron 12+已支持ES模块);若为渲染进程,需在BrowserWindow配置中启用nodeIntegration和contextIsolation: false(或使用预加载脚本处理文件读取)。
内容的提问来源于stack exchange,提问作者Aristocrates
相关产品推荐
相关产品推荐

