Nodejs下载文件

dhso
2018/06/27 16:58
统计中
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;
      }
    }
  }

}

本文为 dhso 原创

发布在 http://blog.minws.com/nodejsxia-zai-wen-jian/

如有转载,请标明来源!

作者信息
姓名:dhso
热评文章
最新评论
文章概览