Per “fs.readFileSync(filename, ‘utf8’) doesn’t strip BOM markers #1918”, fs.readFile
is working as designed: BOM is not stripped from the header of the UTF-8 file, if it exists. It at the discretion of the developer to handle this.
Possible workarounds:
data = data.replace(/^\uFEFF/, '');
per https://github.com/joyent/node/issues/1918#issuecomment-2480359- Transform the incoming stream to remove the BOM header with the NPM module
bomstrip
per https://github.com/joyent/node/issues/1918#issuecomment-38491548
What you are getting is the byte order mark header (BOM) of the UTF-8 file. When JSON.parse
sees this, it gives an syntax error (read: “unexpected character” error). You must strip the byte order mark from the file before passing it to JSON.parse
:
fs.readFile('./myconfig.json', 'utf8', function (err, data) {
myconfig = JSON.parse(data.toString('utf8').replace(/^\uFEFF/, ''));
});
// note: data is an instance of Buffer