Home >Web Front-end >Front-end Q&A >How to convert encoding gbk to utf8 in nodejs

How to convert encoding gbk to utf8 in nodejs

青灯夜游
青灯夜游Original
2021-09-16 12:19:295508browse

Conversion method: 1. Use the "new TextDecoder('gbk').decode(new Uint8Array([...]).buffer)" statement; 2. Use "iconv.decode(Buffer.from( [...]), 'gbk')" statement.

How to convert encoding gbk to utf8 in nodejs

The operating environment of this tutorial: windows7 system, nodejs version 14.15.4, DELL G3 computer.

js and nodejs both have TextEncoder TextDecoder, which can convert between encodings

nodejs version requires >=8.3. 0 only supports util.TextEncoder,util.TextDecoder

##gbk to utf8

new TextDecoder('gbk').decode(new Uint8Array([ 47, 63, 214, 208, 206, 196, 61, 56, 56 ]).buffer)
// out:  "/?中文=88"
nodejs recommended to pass

iconv or iconv-lite Third-party library performs conversion between encodings. Because using the native TextEncoder requires complete ICU Data, see here for detailsutil_class_util_textdecoder

utf8 gbk mutual conversion

let iconv = require('iconv-lite');
// 这里是utf8
let str = '/?中文=88';
// utf8转换成gbk
let encoded = iconv.encode(str, 'gbk');
console.log(encoded,encoded.toJSON())

// gbk转换成utf8
str = iconv.decode(Buffer.from([ 47, 63, 214, 208, 206, 196, 61, 56, 56 ]), 'gbk');
console.log('utf8 str:',str)

// out: Buffer <2F, 3F, D6, D0, CE, C4, 3D, 38, 38>
// Object {data: [47, 63, 214, 208, 206, 196, 61, 56, 56], type: "Buffer"}
// utf8 str: "/?中文=88"
【Recommended Study: "

nodejs tutorial"】

The above is the detailed content of How to convert encoding gbk to utf8 in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn