Home >Web Front-end >JS Tutorial >Things to note when formatting JSON files with NodeJs
A lightning point accidentally discovered when developing NodeJs
Under normal circumstances, there is no problem after reading characters from the JSON file and then passing JSON.parse, as long as the format is correct
Sometimes When ensuring that the JSON format is correct, the unexpected token exception still occurs
After investigation, it was found that there are unicode characters that will not be displayed
So it was determined to be a UTF-8 problem. UTF-8 points have a dom version. And the dom-free version, generally the editor will save it as utf8 with dom by default if it is not deliberately set.
The solution is to first convert the read file into binary, then retrieve the dom symbol and delete the
code Implementation part
function readText(pathname) { var bin = fs.readFileSync(pathname); if (bin[0] === 0xEF && bin[1] === 0xBB && bin[2] === 0xBF) { bin = bin.slice(3); } return bin.toString('utf-8'); }
For more related articles on matters needing attention when formatting JSON files read by NodeJs, please pay attention to the PHP Chinese website!