Nodejs下载文件

2018-06-27 / 0 评论 / 77 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2021年11月03日,已超过202天没有更新,若内容或图片失效,请留言反馈。
function downloadFile(_url, _filename, _rewrite, _startFunc, _endFunc, _errorFunc) {  if (!_filename) {
    let us = _url.split('/');
    _filename = us[us.length - 1];
  }
  _mkdirsSync(path.join(app.getPath("userData"), 'resources'));
  let _realpath = path.join(app.getPath("userData"), 'resources', _filename);
  if (_rewrite) {
    _download(_url, _realpath);
    return;
  }
  fs.exists(_realpath, (exists) => {
    if (!exists) _download(_url, _realpath);
  })
  function _download(_url, _realpath) {
    http.get(_url, (response) => {
      if (typeof _startFunc === "function") _startFunc(_realpath);
      response.pipe(fs.createWriteStream(_realpath));
      response.on('error', function () {
        if (typeof _errorFunc === "function") _errorFunc(_realpath);
      })
      response.on('end', function () {
        let _realpathDir = _realpath.split('.');
        _realpathDir.pop();
        fs.createReadStream(_realpath).pipe(unzipper.Extract({ path: _realpathDir.join('') }));
        if (typeof _endFunc === "function") _endFunc(_realpath);
      })
    })
  }
  function _mkdirsSync(dirname, mode) {
    if (fs.existsSync(dirname)) {
      return true;
    } else {
      if (_mkdirsSync(path.dirname(dirname), mode)) {
        fs.mkdirSync(dirname, mode);
        return true;
      }
    }
  }
}

0

评论 (0)

取消