将流式缓冲区转换为utf8-string

Big*_*gie 172 node.js

我想使用node.js发出HTTP请求,从Web服务器加载一些文本.由于响应可以包含很多文本(几兆字节),我想分别处理每个文本块.我可以使用以下代码实现此目的:

var req = http.request(reqOptions, function(res) {
    ...
    res.setEncoding('utf8');
    res.on('data', function(textChunk) {
        // process utf8 text chunk
    });
});
Run Code Online (Sandbox Code Playgroud)

这似乎没有问题.但是我想支持HTTP压缩,所以我使用zlib:

var zip = zlib.createUnzip();

// NO res.setEncoding('utf8') here since we need the raw bytes for zlib
res.on('data', function(chunk) {
    // do something like checking the number of bytes downloaded
    zip.write(chunk); // give the raw bytes to zlib, s.b.
});

zip.on('data', function(chunk) {
    // convert chunk to utf8 text:
    var textChunk = chunk.toString('utf8');

    // process utf8 text chunk
});
Run Code Online (Sandbox Code Playgroud)

对于'\u00c4'包含两个字节的多字节字符,这可能是一个问题:0xC30x84.如果第一个字节被第一个chunk(Buffer)覆盖,第二个字节被第二个字节覆盖,那么chunk.toString('utf8')将在文本块的结尾/开头产生不正确的字符.我怎么能避免这个?

提示:我仍然需要缓冲区(更具体地说是缓冲区中的字节数)来限制下载的字节数.因此res.setEncoding('utf8'),对于非压缩数据,使用上面第一个示例代码中的内容并不符合我的需求.

Big*_*gie 276

单缓冲区

如果您有单个Buffer,则可以使用其toString方法将使用特定编码将全部或部分二进制内容转换为字符串.默认情况下,utf8如果您不提供参数,但我在此示例中明确设置了编码.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});
Run Code Online (Sandbox Code Playgroud)

流式缓冲器

如果您有像上面问题中的流式缓冲区,其中多字节字符的第一个字节UTF8可能包含在第一个Buffer(块)中,第二个字节可能包含在第二个字节中,Buffer那么您应该使用a StringDecoder.:

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});
Run Code Online (Sandbox Code Playgroud)

这样就可以通过直到将所有必需字节写入解码器来缓冲不完整字符的StringDecoder字节.

  • 你也可以chunk.toString('utf8'); (62认同)
  • @joshperry:sry,但正如我的问题文本所解释的那样:`chunk.toString('utf8')`并不总是有效,因为UTF8中有多字节字符.我不明白为什么你改变了我的答案,通过使用`StringDecoder`明确克服了这个问题.我在这里想念一下吗?`node`改变了什么? (8认同)
  • 我更改了主题标题并编辑了答案.它现在显示了两种解决方案:使用`toString`转换流缓冲区和单个缓冲区. (7认同)