Home >Web Front-end >JS Tutorial >Things to note when formatting JSON files with NodeJs

Things to note when formatting JSON files with NodeJs

高洛峰
高洛峰Original
2017-01-04 16:48:321529browse

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!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn