javascriptreadfilecp1251

fs.readFileSync("./bank/"+client,'cp1251'); is throwing throw new ERR_INVALID_OPT_VALUE_ENCODING


I'm trying read from a file (The file is in Bulgarian) and with utf 8 it returns nonsense characters so I tried cp1251 but it throws: ERR_INVALID_OPT_VALUE_ENCODING.

var str = fs.readFileSync("./bank1/"+client,'cp1251');

Solution

  • Install iconv:

    npm install iconv
    

    Use the code to read file encoded in cp1251:

    const fs = require('fs');
    var Iconv = require('iconv').Iconv;
    var iconv = new Iconv('cp1251', 'utf-8');
    const encoded = fs.readFileSync("./bank1/"+client);
    const decoded = iconv.convert(encoded).toString();