@@ -53,11 +53,12 @@ class JSONParseError extends SyntaxError {
53
53
}
54
54
55
55
const parseJson = ( txt , reviver , context ) => {
56
+ const parseText = stripBOM ( txt )
56
57
context = context || 20
57
58
try {
58
- return JSON . parse ( txt , reviver )
59
+ return JSON . parse ( parseText , reviver )
59
60
} catch ( e ) {
60
- if ( typeof txt !== 'string' ) {
61
+ if ( typeof txt !== 'string' && ! Buffer . isBuffer ( txt ) ) {
61
62
const isEmptyArray = Array . isArray ( txt ) && txt . length === 0
62
63
throw Object . assign ( new TypeError (
63
64
`Cannot parse ${ isEmptyArray ? 'an empty array' : String ( txt ) } `
@@ -67,9 +68,14 @@ const parseJson = (txt, reviver, context) => {
67
68
} )
68
69
}
69
70
70
- throw new JSONParseError ( e , txt , context , parseJson )
71
+ throw new JSONParseError ( e , parseText , context , parseJson )
71
72
}
72
73
}
73
74
75
+ // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
76
+ // because the buffer-to-string conversion in `fs.readFileSync()`
77
+ // translates it to FEFF, the UTF-16 BOM.
78
+ const stripBOM = txt => String ( txt ) . replace ( / ^ \uFEFF / , '' )
79
+
74
80
module . exports = parseJson
75
81
parseJson . JSONParseError = JSONParseError
0 commit comments