【问题标题】:using shell.openItem() to open a file in an asar archive使用 shell.openItem() 打开 asar 存档中的文件
【发布时间】:2017-12-10 16:38:37
【问题描述】:

我有一个使用 app.asar 文件的电子应用程序。我希望能够在默认 Windows 应用程序(即 Excel)中打开 asar 文件中的文件 (.xlsx)。我试过了

let xlsx = path.join(__dirname + '/path/to/app.asar/path/to/file');
shell.openItem(xlsx);

但它不起作用(没有错误,文件没有打开)。

我可以用 fs 读取文件

let xlsx = path.join(__dirname + '/path/to/app.asar/path/to/file');
fs.readFileSync(xlsx);

但我无法在 Excel 中打开文件。

【问题讨论】:

    标签: node.js electron


    【解决方案1】:

    来自Application Packaging的文档

    asar 存档是一种类似 tar 的简单格式,可将文件连接成单个文件。 Electron 可以从中读取任意文件,而无需解压整个文件。

    只有 Electron 可以访问这些文件,Excel 和其他应用程序根本无法处理 asar 档案。

    您可以将文件从 asar 存档复制到系统的临时文件夹并从那里打开它。像这样:

    const fs = require('fs')
    const path = require('path')
    const {shell, app} = require('electron')
    
    let xlsx = path.join(__dirname,'/path/to/app.asar/path/to/file')
    let xlsxtmp = üath.join(app.getPath('temp', 'file')
    let ws = fs.createWriteStream(xlsxtmp)
    
    fs.createReadStream(xlsx).pipe(ws)
    
    ws.on('finish', () => {
        shell.openItem(xlsxtmp);
    }
    

    另一种选择是不将该 xlsx 打包到存档中,而是将其下载到 userData 路径中。

    【讨论】:

    • 成功了,谢谢!我只需要做一些调整:let xlsx = path.join(__dirname + '/path/to/file')let xlsxtmp = path.join(app.getPath('temp'),'file')。我还发现__dirname 解析为C:\path\to\app\resources\app.asar 而不仅仅是C:\path\to\app 这真的让我有一阵子失望。
    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    相关资源
    最近更新 更多