Node.js字符串解码器StringDecoder

本文概述

Node.js StringDecoder用于将缓冲区解码为字符串。它类似于buffer.toString(), 但为UTF提供了额外的支持。

你需要使用require(‘string_decoder’)来使用StringDecoder模块。

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

Node.js StringDecoder方法

StringDecoder类只有两个方法。

Method Description
coder.write(缓冲区) 它用于返回解码后的字符串。
coder.end() 如果缓冲区中还有剩余字节, 则用于返回尾随字节。

Node.js StringDecoder示例

我们来看一个简单的Node.js StringDecoder示例。

文件:stringdecoder_example1.js

const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');

const buf1 = new Buffer('this is a test');
console.log(decoder.write(buf1));//prints: this is a test

const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');
console.log(decoder.write(buf2));//prints: this is a test

const buf3 = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
console.log(decoder.write(buf3));//prints: buffer
Node.js字符串解码器示例1

来源:

https://www.srcmini02.com/27997.html

微信公众号
手机浏览(小程序)
0
分享到:
没有账号? 忘记密码?