我在服务器端使用 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)
// ....
})
Run Code Online (Sandbox Code Playgroud)
我应该等待诸如 response.on('end') 之类的东西吗?
我正在做的目的是获取缓冲区的大小(我可以通过 writer.getBuffer() 获取)
感谢您的任何提示!
我发现要下载流,在我的内存中,我必须等待 writer 上的事件 (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
Run Code Online (Sandbox Code Playgroud)
然后在我的下载功能中:
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'})
});
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10434 次 |
| 最近记录: |