我在服务器端上使用axios。
我想下载大文件..从技术上讲,这应该与字节范围一起使用
在下面的代码中:
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()来获取
感谢任何提示!
答案 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'})
});
})