module iconv
iconv
It is a built-in conversion module used to realize data conversion between various different encodings.
iconv is implemented by calling the encoding function of the underlying system, and also supports some built-in encoding sets, such as "utf8", "utf-8", "ucs2", "ucs-2", "utf16", "utf-16" , "ucs2le", "ucs-2le", "utf16le", "utf-16le", "ucs2be", "ucs-2be", "utf16be", "utf-16be", "ucs4", "ucs-4" , "utf32", "utf-32", "ucs4le", "ucs-4le", "utf32le", "utf-32le", "ucs4be", "ucs-4be", "utf32be", "utf-32be"
iconv
The module provides two core methods:
iconv.encode(charset, data)
:Convert text data to binary dataiconv.decode(charset, data)
:Convert binary data to text data
These two methods are very easy to use and understand. For example, for a "utf-8" encoded string "hello", we can convert it to "gbk" encoding through the following code:
1
2
3
4
5const iconv = require('iconv');
const utf8String = 'hello';
const gbkString = iconv.decode('gbk', iconv.encode('utf-8', utf8String));
console.log(gbkString); // output "你好"
Note: The first parameter charset of encode
the and decode
methods both specify the encoding to be used.
static function
encode
Convert text to binary data using iconv
1
2static Buffer iconv.encode(String charset,
String data);
Call parameters:
- charset: String, specified character set
- data: String, the text to be converted
Return results:
- Buffer, returns the decoded binary data
decode
Use iconv toBufferConvert content to text
1
2static String iconv.decode(String charset,
Buffer data);
Call parameters:
- charset: String, specified character set
- data:Buffer, the binary data to be converted
Return results:
- String, returns the encoded string
isEncoding
Check if character set is supported
1static Boolean iconv.isEncoding(String charset);
Call parameters:
- charset: String, specified character set
Return results:
- Boolean, returns whether the character set is supported