Skip to content

Commit 38dadad

Browse files
committed
Moved readFileSync within the try/catch to prevent filesystem errors when a file was not present. The error when throws is true is the same as before, but when it's false the error is swallowed and the return is null.
Added tests for readFileSync.
1 parent 9827260 commit 38dadad

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

index.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,9 @@ function readFileSync (file, options) {
6363
shouldThrow = options.throws
6464
}
6565

66-
var content = fs.readFileSync(file, options)
67-
content = stripBom(content)
68-
6966
try {
67+
var content = fs.readFileSync(file, options)
68+
content = stripBom(content)
7069
return JSON.parse(content, options.reviver)
7170
} catch (err) {
7271
if (shouldThrow) {

test/read-file-sync.test.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,14 +98,29 @@ describe('+ readFileSync()', function () {
9898
})
9999

100100
describe('> when invalid JSON and throws set to true', function () {
101-
it('should return null', function () {
101+
it('should throw an exception', function () {
102102
var file = path.join(TEST_DIR, 'somefile4-invalid.json')
103103
var data = '{not valid JSON'
104104
fs.writeFileSync(file, data)
105105

106106
assert.throws(function () {
107-
jf.readFileSync(file)
107+
jf.readFileSync(file, {throws: true})
108108
})
109+
})
110+
})
111+
112+
describe('> when json file is missing and throws set to false', function () {
113+
it('should return null', function () {
114+
var file = path.join(TEST_DIR, 'somefile4-invalid.json')
115+
116+
var obj = jf.readFileSync(file, {throws: false})
117+
assert.strictEqual(obj, null)
118+
})
119+
})
120+
121+
describe('> when json file is missing and throws set to true', function () {
122+
it('should throw an exception', function () {
123+
var file = path.join(TEST_DIR, 'somefile4-invalid.json')
109124

110125
assert.throws(function () {
111126
jf.readFileSync(file, {throws: true})

0 commit comments

Comments
 (0)