diff --git a/index.js b/index.js index 45bf86d..135d8c7 100644 --- a/index.js +++ b/index.js @@ -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 @@ -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) { @@ -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 { @@ -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) {