Skip to content

Commit 0b494c4

Browse files
authored
Merge pull request #82 from jprichardson/writefile
Don't write if there is a serialisation error & no callback passed
2 parents fed4d8b + 1b77bc6 commit 0b494c4

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,9 @@ function writeFile (file, obj, options, callback) {
9494
try {
9595
str = JSON.stringify(obj, options ? options.replacer : null, spaces) + '\n'
9696
} catch (err) {
97-
if (callback) return callback(err, null)
97+
// Need to return whether a callback was passed or not
98+
if (callback) callback(err, null)
99+
return
98100
}
99101

100102
fs.writeFile(file, str, options, callback)

test/write-file.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,4 +118,22 @@ describe('+ writeFile()', function () {
118118
})
119119
})
120120
})
121+
122+
// Prevent https://github.com/jprichardson/node-jsonfile/issues/81 from happening
123+
describe("> when callback isn't passed & can't serialize", function () {
124+
it('should not write an empty file', function (done) {
125+
this.slow(1100)
126+
var file = path.join(TEST_DIR, 'somefile.json')
127+
var obj1 = { name: 'JP' }
128+
var obj2 = { person: obj1 }
129+
obj1.circular = obj2
130+
131+
jf.writeFile(file, obj1)
132+
133+
setTimeout(function () {
134+
assert(!fs.existsSync(file))
135+
done()
136+
}, 1000)
137+
})
138+
})
121139
})

0 commit comments

Comments
 (0)