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 3, 2017
1 parent 3dbf42a commit 66a3363
Showing 1 changed file with 8 additions and 1 deletion.
9 changes: 8 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,17 @@ module.exports = Installer

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

function stripBOM (str) {
if (str.charCodeAt(0) === 0xFEFF) {
str = str.slice(1)
}
return str
}

0 comments on commit 66a3363

Please sign in to comment.