|
Last change
on this file was 9af201e, checked in by MBK <marija.karapandzova@…>, 13 days ago |
|
Fix frontend appearance
|
-
Property mode
set to
100644
|
|
File size:
1.0 KB
|
| Line | |
|---|
| 1 | /*
|
|---|
| 2 | MIT License http://www.opensource.org/licenses/mit-license.php
|
|---|
| 3 | */
|
|---|
| 4 |
|
|---|
| 5 | "use strict";
|
|---|
| 6 |
|
|---|
| 7 | const JSONParseError = require("../errors/JSONParseError");
|
|---|
| 8 |
|
|---|
| 9 | /** @typedef {import("../util/fs").JsonValue} JsonValue */
|
|---|
| 10 |
|
|---|
| 11 | // Inspired by https://github.com/npm/json-parse-even-better-errors
|
|---|
| 12 |
|
|---|
| 13 | // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
|
|---|
| 14 | // because the buffer-to-string conversion in `fs.readFileSync()`
|
|---|
| 15 | // translates it to FEFF, the UTF-16 BOM.
|
|---|
| 16 | /**
|
|---|
| 17 | * @param {string | Buffer} txt text
|
|---|
| 18 | * @returns {string} text without BOM
|
|---|
| 19 | */
|
|---|
| 20 | const stripBOM = (txt) => String(txt).replace(/^\uFEFF/, "");
|
|---|
| 21 |
|
|---|
| 22 | /**
|
|---|
| 23 | * @template [R=JsonValue]
|
|---|
| 24 | * @callback ParseJsonFn
|
|---|
| 25 | * @param {string} raw text
|
|---|
| 26 | * @param {(this: EXPECTED_ANY, key: string, value: EXPECTED_ANY) => EXPECTED_ANY=} reviver reviver
|
|---|
| 27 | * @returns {R} parsed JSON
|
|---|
| 28 | */
|
|---|
| 29 |
|
|---|
| 30 | /** @type {ParseJsonFn} */
|
|---|
| 31 | const parseJson = (raw, reviver) => {
|
|---|
| 32 | const txt = stripBOM(raw);
|
|---|
| 33 |
|
|---|
| 34 | try {
|
|---|
| 35 | return JSON.parse(txt, reviver);
|
|---|
| 36 | } catch (err) {
|
|---|
| 37 | throw new JSONParseError(/** @type {Error} */ (err), raw, txt);
|
|---|
| 38 | }
|
|---|
| 39 | };
|
|---|
| 40 |
|
|---|
| 41 | module.exports = parseJson;
|
|---|
Note:
See
TracBrowser
for help on using the repository browser.