Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

readFile JSON parse error includes filename #34

Merged
merged 2 commits into from
Oct 14, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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