I want to get a file from a swift container in node.
我想从节点中的swift容器中获取文件。
I'm using this code for making a request (largely inspired by this code):
我正在使用此代码发出请求(主要受此代码启发):
var client = https.request(options, function(res) {
var buffers = [];
res.body='';
res.on('data', function(buffer) {
buffers.push(buffer);
});
res.on('end', function(err){
res.body = buffers.join('');
callback && callback(res);
});
});
If download a text file, there's no problem, but for binary data, differences appears between the downloaded file and the original, after some bytes (258 with an mp3 file).
如果下载文本文件,没有问题,但对于二进制数据,在一些字节(带有mp3文件的258)之后,下载的文件和原始文件之间会出现差异。
Have you an idea of what could cause a such corruption? character encoding, ending characters which I have to remove,wrong way to merge the datas,...
你知道什么可能导致这样的腐败吗?字符编码,我必须删除的结束字符,合并数据的错误方法,...
update
更新
I made it work like that:
我让它像那样工作:
var client = https.request(options, function(res) {
res.body='';
res.on('data', function(buffer) {
res.body+= buffer.toString('binary');
});
res.on('end', function(err){
callback && callback(res);
});
});
but it's written in the doc that toString('binary') will be deprecated soon, so it's not the best solution.
但是在文档中写道,toString('binary')很快就会被弃用,所以它不是最好的解决方案。
1 个解决方案
#1
0
buffers.join('');
Does a string join on the array, which is not what you want for binary data. The correct way to concatenate buffers is
字符串是否在数组上连接,这不是您想要的二进制数据。连接缓冲区的正确方法是
Buffer.concat(buffers);
See http://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
见http://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
So you could do this
所以你可以做到这一点
var client = https.request(options, function(res) {
var buffers=[];
res.on('data', function(buffer) {
buffers.push(buffer);
});
res.on('end', function(err){
res.body=Buffer.concat(Buffers);
callback && callback(res);
});
});
But your callback would have to be expecting a Buffer rather than a String. Of course, being binary data, it shouldn't be a String anyway.
但是你的回调必须要求一个Buffer而不是一个String。当然,作为二进制数据,它无论如何都不应该是String。
#1
0
buffers.join('');
Does a string join on the array, which is not what you want for binary data. The correct way to concatenate buffers is
字符串是否在数组上连接,这不是您想要的二进制数据。连接缓冲区的正确方法是
Buffer.concat(buffers);
See http://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
见http://nodejs.org/api/buffer.html#buffer_class_method_buffer_concat_list_totallength
So you could do this
所以你可以做到这一点
var client = https.request(options, function(res) {
var buffers=[];
res.on('data', function(buffer) {
buffers.push(buffer);
});
res.on('end', function(err){
res.body=Buffer.concat(Buffers);
callback && callback(res);
});
});
But your callback would have to be expecting a Buffer rather than a String. Of course, being binary data, it shouldn't be a String anyway.
但是你的回调必须要求一个Buffer而不是一个String。当然,作为二进制数据,它无论如何都不应该是String。