Skip to content

Commit

Permalink
Merge pull request #34 from charlierudolph/cr-readError
Browse files Browse the repository at this point in the history
readFile JSON parse error includes filename
  • Loading branch information
jprichardson committed Oct 14, 2015
2 parents 9b6d708 + 356b823 commit 93ccd05
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 6 deletions.
15 changes: 9 additions & 6 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ function readFile (file, options, callback) {
try {
obj = JSON.parse(data, options ? options.reviver : null)
} catch (err2) {
err2.message = file + ': ' + err2.message
return callback(err2)
}

Expand All @@ -27,13 +28,15 @@ function readFileSync (file, options) {
}

var shouldThrow = 'throws' in options ? options.throws : true
var content = fs.readFileSync(file, options)

if (shouldThrow) { // i.e. throw on invalid JSON
return JSON.parse(fs.readFileSync(file, options), options.reviver)
} else {
try {
return JSON.parse(fs.readFileSync(file, options), options.reviver)
} catch (err) {
try {
return JSON.parse(content, options.reviver)
} catch (err) {
if (shouldThrow) {
err.message = file + ': ' + err.message
throw err
} else {
return null
}
}
Expand Down
15 changes: 15 additions & 0 deletions test/read-file-sync.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ describe('+ readFileSync()', function () {
}
})

describe('> when invalid JSON', function () {
it('should include the filename in the error', function () {
var file = path.join(TEST_DIR, 'somefile.json')
fs.writeFileSync(file, '{')

assert.throws(function () {
jf.readFileSync(file)
}, function (err) {
assert(err instanceof Error)
assert(err.message.match(file))
return true
})
})
})

describe('> when invalid JSON and throws set to false', function () {
it('should return null', function () {
var file = path.join(TEST_DIR, 'somefile4-invalid.json')
Expand Down
13 changes: 13 additions & 0 deletions test/read-file.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,19 @@ describe('+ readFile()', function () {
})
})

describe('> when invalid JSON', function () {
it('should include the filename in the error', function (done) {
var file = path.join(TEST_DIR, 'somefile.json')
fs.writeFileSync(file, '{')

jf.readFile(file, function (err, obj2) {
assert(err instanceof Error)
assert(err.message.match(file))
done()
})
})
})

describe('> when JSON reviver is set', function () {
it('should transform the JSON', function (done) {
var file = path.join(TEST_DIR, 'somefile.json')
Expand Down

0 comments on commit 93ccd05

Please sign in to comment.