Nodejs功能模块:

简介如下:
fs => 用来创建读写流
详情请查询Nodejs官网:http://nodejs.cn/api/http.html

方法功能:
服务器:文件以buffer流传输到前端(application/octet-stream)
例如:在这里插入图片描述
本地:存储到本地 => 源文件(压缩包可选择直接解压到本地)

代码如下:
/**
 * 下载Blob到本地(zip,tar,exe,dll,jpg)
 * @param {String} fileName 例:
 * @param {String} outPutPath 例: path.join(process.cwd(), 'userData');
 * @param {String} outPutName 例: jdk-8u181-linux-x64.tar.gz
 * @param callback '() => {}';
 */
let downloadRequest, CancelToken = axios.CancelToken;
export let _downLoadBlob2Local = (fileName, outPutPath, outPutName, callback) => {
  let streamLocal;
  if (outPutName) {
    streamLocal = new WritableStream(fs.createWriteStream(path.join(outPutPath, outPutName)));
  }
  axios.post('URL路径', { '参数': fileName }, {
    responseType: 'blob', // 重点
    onDownloadProgress: (event) => { // 下载进度
      // event.total为0时
      let total = event.target.getResponseHeader('Content-Length');
      // event.total不为0
      // let percentage = parseInt((event.loaded / event.total) * 100)
      let percentage = parseInt((event.loaded / total) * 100) > 100 ? 100 : parseInt((event.loaded / total) * 100);
      console.log('percentage:', percentage);
    },
    cancelToken: new CancelToken(function executor (c) { // 取消下载
      downloadRequest = c;
    })
  }).then((res) => {
    if (res.status === 200) {
      let blob = new Blob([res.data]);
      if (streamLocal) {
        // 生成源文件
        blob.stream().pipeTo(streamLocal);
        callback && callback();
      } else {
        // 通过JSZip直接解压到本地
        buffer2files(blob, outPutPath, fileName, callback);
      }
    } else {
      alert('错误码:' + res.status);
    }
  }).catch(err => { throw err })
}

/**
  * 取消下載
  * @param callback '() => {}';
  */
export let _abortDownload = (callback) => {
  downloadRequest();
  callback && callback();
}

/**
  * buffer格式的内容写到对应的目录
  * @param {Object}  file zip 本地或远程读取的文件
  * @param {String}  outPutPath 例: path.join(process.cwd(), 'userData');
  * @param callback '() => {}';
  */
export let buffer2files = (file, outPutPath, fileName, callback) => {
  let newZip = new JSZip();
  let jszipresults = [];
  let jszipresult = () => {
    return new Promise(resolve => {
      newZip.loadAsync(file)
        .then((file) => {
          dofile(newZip, outPutPath, file);
          resolve();
        });
    });
  };
  jszipresults.push(jszipresult());
  Promise.all(jszipresults).then(() => {
    // 解压后删除zip文件
    (fileName && fs.existsSync(path.join(outPutPath, fileName + '.zip'))) && fs.unlinkSync(path.join(outPutPath, fileName + '.zip'))
    callback && callback();
  });
}

/**
  * 解压相关
  * @param {Object}  newZip
  * @param {String}  outPutPath
  * @param {Object}  file
  */
let dofile = (newZip, outPutPath, file) => {
  let files = file.files;
  for (let f in files) {
    let zipObj = files[f];
    let fileName = f.substring(f.lastIndexOf('/') + 1);
    let filePath = f.substring(0, f.lastIndexOf('/') + 1);
    !zipObj.dir && newZip.file(f).async('nodebuffer') // 读取压缩包中文件
      .then(function (content) {
        // 生成文件/文件夹
        fs.mkdirSync(path.join(outPutPath, filePath), { recursive: true });
        // 写入本地
        _writeTxtToFileSync(path.join(outPutPath, filePath, fileName), content)
      });
  }
}

/**
  * 同步写入
  * @param {String} fullPath 路径 例:xx/x/x.json
  * @param {String} newTxt,写入到文件的字符串数据
  */
export let _writeTxtToFileSync = (fullPath, newTxt) => {
  try {
    fs.writeFileSync(fullPath, newTxt);
  } catch (e) {
    alert(e);
    console.error(e);
  }
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐