What is encoding?
The 'encoding' npm package provides utilities for encoding and decoding text in various character encodings. It's often used to convert between different encodings, such as from UTF-8 to ISO-8859-1, or to handle text data that may not be in a standard encoding format.
What are encoding's main functionalities?
Convert encoding of text
This feature allows you to convert a string from one encoding to another. In the code sample, a UTF-8 encoded string is converted to ISO-8859-1.
const encoding = require('encoding');
const utf8String = 'Some UTF-8 text';
const isoString = encoding.convert(utf8String, 'ISO-8859-1');
Decode buffer to string
This feature decodes a buffer into a string using a specified character encoding. In the code sample, a binary encoded buffer is decoded into a UTF-8 string.
const encoding = require('encoding');
const buffer = Buffer.from('encoded text', 'binary');
const decodedString = encoding.convert(buffer, 'utf-8').toString();
Other packages similar to encoding
iconv-lite
iconv-lite is a popular encoding conversion library that offers similar functionalities to 'encoding'. It supports numerous encodings and is often used for converting buffers to different character encodings. Unlike 'encoding', it does not rely on native Node.js modules and is purely JavaScript, which can be advantageous for compatibility and ease of use.
buffer-encoding
buffer-encoding is another package that provides encoding and decoding functionalities for buffers. It allows for easy conversion between different character encodings. It is similar to 'encoding' but might have a different API or support different sets of encodings.
Encoding
encoding is a simple wrapper around node-iconv and iconv-lite to convert strings from one encoding to another. If node-iconv is not available for some reason,
iconv-lite will be used instead of it as a fallback.
Install
Install through npm
npm install encoding
Usage
Require the module
var encoding = require("encoding");
Convert with encoding.convert()
var resultBuffer = encoding.convert(text, toCharset, fromCharset);
Where
- text is either a Buffer or a String to be converted
- toCharset is the characterset to convert the string
- fromCharset (optional, defaults to UTF-8) is the source charset
Output of the conversion is always a Buffer object.
Example
var result = encoding.convert("ÕÄÖÜ", "Latin_1");
console.log(result); //<Buffer d5 c4 d6 dc>
iconv support
By default only iconv-lite is bundled. If you need node-iconv support, you need to add it
as an additional dependency for your project:
...,
"dependencies":{
"encoding": "*",
"iconv": "*"
},
...
License
MIT