electron 读取asar后无法删除
electron读取asar文件后,其中的文件和目录被打包成一个只读文件系统,因此无法直接删除其中的文件。如果需要删除某个文件,可以先将该文件从asar中解包出来,然后再进行删除操作。具体步骤如下:
- 使用fs模块的readFileSync读取asar文件,将其内容解压到一个临时目录中。
const fs = require('fs');
const path = require('path');
const asar = require('asar');
const asarPath = path.join(__dirname, 'app.asar');
const tempDir = path.join(__dirname, 'temp');
asar.extractAll(asarPath, tempDir);
- 对临时目录中的文件进行修改、添加、删除等操作。
const filePath = path.join(tempDir, 'file.txt');
// 修改文件内容
fs.writeFileSync(filePath, 'new content');
// 添加新文件
fs.writeFileSync(path.join(tempDir, 'newfile.txt'), 'new file content');
// 删除文件
fs.unlinkSync(filePath);
- 将修改后的文件重新打包成asar文件,并将临时文件夹删除。
asar.createPackage(tempDir, asarPath);
fs.rmdirSync(tempDir, { recursive: true });
需要注意的是,使用上述方法修改了asar文件后,需要重新启动electron程序才能生效
原文地址: https://www.cveoy.top/t/topic/eEJW 著作权归作者所有。请勿转载和采集!