NodeJs:以ff.createReadStream二进制形式以UTF-8格式流式传输 [英] NodeJs: binary fs.createReadStream streamed as UTF-8

查看:530
本文介绍了NodeJs:以ff.createReadStream二进制形式以UTF-8格式流式传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我手头的任务是在NodeJs中读取一个jpeg文件,并将其作为http响应发送,以响应服务器请求.似乎微不足道.但是,我的第一个解决方案失败了.浏览器确实收到了一些二进制文件,比原始文件大30%.

My task at hand was to read a jpeg file in NodeJs and send it as http-response to answer a server request. Seemed to be trivial. However, my first solution failed. The browser did receive some binary gibrish, that was about 30% larger than the original file.

我的代码为(简体; res的类型为SeverResponse):

My code was (simplified; res is of type SeverResponse):

...
var fs = require('fs');
var stream = fs.createReadStream(pathToJPEG, {encoding: 'binary'});
res.setHeader('Content-Type', "image/jpeg");
stream.pipe(res);
...

事实证明,到达浏览器的是我的源数据的UTF-8编码版本.我还能够排除响应对象是罪魁祸首.当我给它一个替代流(来自Buffer而不是文件)时,它工作正常.

As it turned out, what arrived at the browser was the UTF-8 encoded version of my source data. I also was able to exlude the response object to be the culprit. When I gave it an alternative stream (from Buffer, not file) it worked just fine.

结果证明,解决我的问题的方法是删除选项{encoding:'binary'}.这样,我的浏览器就会收到正确的图片:

Turns out the solution to my problem was to drop the option {encoding: 'binary'}. With that my browser received the right picture:

...
var fs = require('fs');
var stream = fs.createReadStream(pathToJPEG);
res.setHeader('Content-Type', "image/jpeg");
stream.pipe(res);
...

我的问题是:为什么?

My question is: Why?

第一个非工作版本应该是正确的版本,这似乎很直观,因为它明确声明了如何读取文件.

It seems intuitive that the first non-working version should be the correct one since it explicitly declares how to read the file.

推荐答案

这是因为binary编码不是真正的binary. createReadStream使用与Buffer相同的encoding参数.从节点缓冲区文档:

This is because the binary encoding is not really binary. createReadStream uses the same encoding parameters that accepted by Buffer. From the Node Buffer Docs:

'binary'-将缓冲区编码为一个字节(即latin-1)编码字符串的方法.不支持字符串"latin-1".相反,只需传递"binary"以使用"latin-1"编码.

'binary' - A way of encoding the buffer into a one-byte (i.e. latin-1) encoded string. The string 'latin-1' is not supported. Instead simply pass 'binary' to use 'latin-1' encoding.

只需将编码设置为null即可获取原始流或缓冲区,或者根本不指定任何内容,就像您在第二个示例中所做的那样.

Just set encoding to null to get the raw stream or buffer, or don't specify anything at all, as you did in your second example.

这篇关于NodeJs:以ff.createReadStream二进制形式以UTF-8格式流式传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆