Resolve ‘Unknown Encoding’ Error for Buffer in Node.js
According to the official document for Buffer implementation, the Buffer class only supports a few encoding charsets including ‘ascii’, ‘utf8′, ‘utf16le’, ‘ucs2′, ‘base64′, ‘binary’, and ‘hex’ [http://nodejs.org/api/buffer.html#buffer_buffer]. So if you’re calling ‘toString’ method from a Buffer instance you should probably get an ‘Unknown Encoding’ error , e.g. reading a text file encoded by ‘latin1′ or ‘ISO-8859-1′. This post provides a quick fix to this problem.
This solution requires iconv. You can install it with npm.
npm install iconv
And then before using Buffer.toString method, override it with the following code.
var Iconv = require('iconv').Iconv;
Buffer.prototype._$_toString = Buffer.prototype.toString;
Buffer.prototype.toString = function(charset) {
if (typeof charset == 'undefined' || charset == 'utf8' || charset == 'utf16le'
|| charset == 'ascii' || charset == 'ucs2' || charset == 'binary'
|| charset == 'base64' || charset == 'hex') {
return this._$_toString.apply(this, arguments);
}
var iconv = new Iconv(charset, 'UTF-8');
var buffer = iconv.convert(this);
var args = arguments;
args[0] = 'utf8';
return buffer.toString.apply(buffer, args);
}
And that’s all.
P.S. This solution is originated from http://stackoverflow.com/questions/14551608/cant-find-encodings-for-node-js