Skip to content

Commit

Permalink
fix: ensure writes are always atomic
Browse files Browse the repository at this point in the history
Fixes: #96
  • Loading branch information
ronag committed Aug 26, 2021
1 parent 494eadd commit 625962d
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ function SonicBoom (opts) {
this._asyncDrainScheduled = false
this.file = null
this.destroyed = false
this.minLength = minLength || 0
this.minLength = Math.min(minLength || 0, MAX_WRITE)
this.sync = sync || false
this.append = append || false
this.mkdir = mkdir || false
Expand Down Expand Up @@ -220,6 +220,10 @@ SonicBoom.prototype.write = function (data) {
throw new Error('SonicBoom destroyed')
}

if (!this._writing && this._buf.length + data.length > MAX_WRITE) {
actualWrite(this)
}

this._buf += data
const len = this._buf.length
if (!this._writing && len > this.minLength) {
Expand Down Expand Up @@ -342,14 +346,9 @@ SonicBoom.prototype.destroy = function () {

function actualWrite (sonic) {
sonic._writing = true
let buf = sonic._buf
const buf = sonic._buf
sonic._buf = ''
const release = sonic.release
if (buf.length > MAX_WRITE) {
buf = buf.slice(0, MAX_WRITE)
sonic._buf = sonic._buf.slice(MAX_WRITE)
} else {
sonic._buf = ''
}
sonic._writingBuf = buf
if (sonic.sync) {
try {
Expand All @@ -368,6 +367,10 @@ function actualClose (sonic) {
sonic.once('ready', actualClose.bind(null, sonic))
return
}
if (sonic._writing) {
sonic.once('drain', actualClose.bind(null, sonic))
return
}
// TODO write a test to check if we are not leaking fds
fs.close(sonic.fd, (err) => {
if (err) {
Expand Down

0 comments on commit 625962d

Please sign in to comment.