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

Things to note when formatting JSON files with NodeJs

高洛峰
Release: 2017-01-04 16:48:32
Original
1533 people have browsed it

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');
}
Copy after login

For more related articles on matters needing attention when formatting JSON files read by NodeJs, please pay attention to the PHP Chinese website!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template