Skip to content

Commit

Permalink
fix: strip BOM when reading JSON files
Browse files Browse the repository at this point in the history
fs.readFile* don't strip the BOM header, even when specifying 'utf8' as
the encoding, and JSON.parse() doesn't handle it either. There are
technically a bunch of BOM indicators, but this is the one seen most
commonly and actually appears in a number of package.json files in the
wild.

See nodejs/node#6924, nodejs/node#3040 for background.
  • Loading branch information
rmg committed Sep 2, 2017
1 parent f631203 commit b87646c
Showing 1 changed file with 6 additions and 1 deletion.
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,16 @@ function main (opts) {

function readJson (jsonPath, name, ignoreMissing) {
return fs.readFileAsync(path.join(jsonPath, name), 'utf8')
.then(str => JSON.parse(str))
.then(stripBOM)
.then(JSON.parse)
.catch({code: 'ENOENT'}, err => {
if (!ignoreMissing) {
throw err
}
})
}

function stripBOM (str) {
return str.replace(/^\uFEFF/, '')
}
}

0 comments on commit b87646c

Please sign in to comment.