NODE.js fs.readFile and the BOM marker
Working on a ReactJS project, got a small glitch while trying to read a JSON file and parse it as a javascript object.
The big issue here is why is this considered correct. The BOM is not part of the string, it's a marker used (and also optional) to aid in how to read the content, but it is not part of the content.
getDataObject() { var dataString = fs.readFileSync("./json/data.json", "utf8"); return JSON.parse(dataString); }
output:
SyntaxError: Unexpected token
SyntaxError: Unexpected token
After checking, double and triple checking again that the file was correct I went deeper and realized that "fs.readFileSync" was returning me the BOM for the UTF file at the beginning of the string. So we just need to strip it out.
getDataObject() { var dataString = fs.readFileSync("./json/data.json", "utf8"); return JSON.parse(dataString.replace(/^\uFEFF/, "")); }I then checked and there are "packages" for this, however I don't think is proper to just import a new dependency just to fix something this small.
The big issue here is why is this considered correct. The BOM is not part of the string, it's a marker used (and also optional) to aid in how to read the content, but it is not part of the content.
Comments