node 远程下载文件,存储本地 - electron,vue

准备工作:

  1. vue 环境
  2. electron 依赖安装 | electron文档指导
  3. node 环境

需求

electron 主窗体 ,子窗体;子窗体 内嵌网页 登录 需要 session 缓存支持

工具文件 tools.ts

  • 远程下载 ,文件以唯一码命名
  • 判断文件是否存在
  • 解压文件

第一步 服务器下载文件

  //导入fs模块
 import fs from  fs
 /**
  * 服务器下载文件 回调函数 downloadFile
  * params => urls,token 请求服务地址,身份验证
  * params => destinationPath 下载后文件临时存储路径 
  * params => sessionPath 解压后session 存储路径
  * params => callBack 回调函数
  */
 downloadFile = (urls:String, destinationPath:any,sessionPath:any,token: any, callBack:any) =>{
      // 判断 文件是否存在
    this.fileExists(destinationPath)
    .then((exists) => {
       if (exists) {
        callBack('exist')
       } else {
        let url = ...server + `/app/base/comm/${urls}`
        const file = fs.createWriteStream(destinationPath);
        https.get(url,{
            headers: {
                Authorization: `Bearer ${token}`
            }
        }, (response: { pipe: (arg0: fs.WriteStream) => void; }) => {
            response.pipe(file);
            file.on('finish', () => {
                file.close(callBack);
            });
        }).on('error', (error: { message: any; }) => {
            fs.unlink(destinationPath,()=>{})
                if (callBack) callBack(error.message)
        });
      }
    }).catch((err) => {
         console.error('发生错误:', err);
    });
 };

第二步 检查相同文件是否存在

    // 文件是否存在 Promise 回调
    fileExists=(path:any)=> {
        return new Promise((resolve) => {
          // 使用 fs.access 检查文件是否存在
          fs.access(path, fs.constants.F_OK, (err) => {
            if (err) {
              resolve(false); // 文件不存在,返回 false
            } else {
              resolve(true); // 文件存在,返回 true
            }
          });
        });
    }

第三步 解压下载文件到指定目录

// 安装解压依赖模块
const admZip = require("adm-zip");

// zipFilePath 临时文件存储位置,destinationPath 解压至该路径
unzipFile=(zipFilePath: any, destinationPath: any) =>{
        return new Promise<void>((resolve, reject) => {
          const zip = new admZip(zipFilePath);
          zip.extractAllTo(destinationPath, true);
          resolve();
        });
    };

使用

利用electron preload 暴露 工具文件 tools.ts

tools.downloadFile(urlStr, zipPath,sessionPath, token, async (error:any)=>{
                if (error) {
                    if(error === 'exist'){
                        console.error('文件存在直接使用');
                                                ... //  进行相关操作
                    } else {
                        console.error('文件下载失败:', error);
                        ElMessage({
                            type: "error",
                            message: "文件下载失败,请重新启动!"
                        });
                        operate_btn_loading.value = false;
                        return;
                    }
                }
                console.log('文件下载完成');
                try {
                    await tools.unzipFile(zipPath,sessionPath);
                    console.log('文件解压完成');
                } catch (err) {
                    console.error(err);
                }
            })
            ElMessage({
                type: "success",
                message: "启动成功!"
            });
        }

子窗体使用

  <!-- 声明 persist_val 变量>
  <webview
    ref="webview"
    ....
    :partition="persist_val"
    ....>
   </webview>

// 通讯后 设置persist_val当前值

persist_val.value = `persist:${data.uid}`
webViewList.value.push({
                    enableremotemodule: true,
                    nodeintegration: true,
                    webpreferences:"nativeWindowOpen=yes,spellcheck=no,contextIsolation=no,sandbox=yes"
                            : "sandbox=no",
                    ...data
                });

END————————
码字不易,如果喜欢或者对你有丝毫帮助的话,帮忙点个👍 哈,点赞就是我的动力。

同时也希望自己能坚持认真的写下去,因为在总结提升自己的同时如果也能帮助更多的前端,那是多么开心的一件事。

小伙伴们 这里有更好的建议或方法,欢迎评论,谢谢。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容