使用流下载大文件时的Axios事件

时间:2019-01-21 18:44:36

标签: node.js axios

我在服务器端上使用axios。

我想下载文件..从技术上讲,这应该与字节范围一起使用

  1. axios是否处理字节范围请求,以便仅在所有响应准备就绪时才调用回调函数
  2. 如果1为不正确,我应该自己处理数据块吗?

在下面的代码中:

axios({
  url: params.url,
  method: 'GET',
  responseType: 'stream' // important
}).then(function (response) {

  logger.debug('__download() : done!')
  let contentType = response.headers['content-type']
  let contentLength = response.headers['content-length']
  var writer = new streams.WritableStream()

  response.data.pipe(writer)
  // ....
})

我应该等待诸如response.on('end')之类的东西吗?

我正在做的目的是获取缓冲区的大小(我可以通过writer.getBuffer()来获取

感谢任何提示!

1 个答案:

答案 0 :(得分:1)

我发现要下载在内存中的流,我不得不在我的作家上等待事件(writer.on('finished',cb)vs response.on ('end',cb))(不确定是否有类似response.on('end')的东西)...

var stream = require('stream');
var util = require('util');
var Writable = stream.Writable;


function MemoryStream(options) {
    if (!(this instanceof MemoryStream)) {
        return new MemoryStream(options);
    }
    Writable.call(this, options); // init super
}
util.inherits(MemoryStream, Writable);

MemoryStream.prototype._write = function (chunk, enc, cb) {
    var buffer = (Buffer.isBuffer(chunk)) ?
        chunk :
        Buffer.alloc(chunk, enc);

    if (Buffer.isBuffer(this.memStore)) {
        this.memStore = Buffer.concat([this.memStore, buffer]);
    } else {
        this.memStore = buffer
    }
    cb();
};


MemoryStream.prototype.toBuffer = function () {
    return this.memStore
};




module.exports = MemoryStream

,然后在我的下载功能中:

axios({
  url: params.url,
  method: 'GET',
  responseType: 'stream' // important
}).then(function (response) {

  logger.debug('__download() : done!')
  let contentType = response.headers['content-type']
  let contentLength = response.headers['content-length']
  var writer = new MemoryStream()

  response.data.pipe(writer)

    writer.on('finish', function () {

        var b = writer.toBuffer()

        let computedContentLength = b.byteLength

        if (!contentLength) { contentLength = computedContentLength }

        return callback(null, { 'foo':'bar'})

    });
})