Skip to content

Commit

Permalink
Do not truncate chunks that are not 100% written
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Nov 7, 2018
1 parent 1cb7ace commit 31cae66
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 3 deletions.
15 changes: 12 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const EventEmitter = require('events')
const flatstr = require('flatstr')
const inherits = require('util').inherits

const maxWriteSize = 4096

function openFile (file, sonic) {
sonic._writing = true
sonic.file = file
Expand Down Expand Up @@ -65,6 +67,13 @@ function SonicBoom (fd, minLength) {
this.emit('error', err)
return
}

if (this._writingBuf.length !== n) {
this._writingBuf = this._writingBuf.slice(n)
fs.write(this.fd, this._writingBuf, 'utf8', this.release)
return
}

this._writingBuf = ''

if (this.destroyed) {
Expand Down Expand Up @@ -193,9 +202,9 @@ SonicBoom.prototype.destroy = function () {
function actualWrite (sonic) {
sonic._writing = true
var buf = sonic._buf
if (buf.length >= 2048) {
buf = sonic._buf.slice(0, 2048)
sonic._buf = sonic._buf.slice(2048)
if (buf.length >= maxWriteSize) {
buf = sonic._buf.slice(0, maxWriteSize)
sonic._buf = sonic._buf.slice(maxWriteSize)
} else {
sonic._buf = ''
}
Expand Down
37 changes: 37 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -433,3 +433,40 @@ test('chunk data accordingly', (t) => {
t.is(code, 0)
})
})

test('write buffers that are not totally written', (t) => {
t.plan(7)

const fakeFs = Object.create(fs)
fakeFs.write = function (fd, buf, enc, cb) {
t.pass('fake fs.write called')
fakeFs.write = fs.write
process.nextTick(cb, null, 0)
}
const SonicBoom = proxyquire('.', {
fs: fakeFs
})

const dest = file()
const fd = fs.openSync(dest, 'w')
const stream = new SonicBoom(fd)

stream.on('ready', () => {
t.pass('ready emitted')
})

t.ok(stream.write('hello world\n'))
t.ok(stream.write('something else\n'))

stream.end()

stream.on('finish', () => {
fs.readFile(dest, 'utf8', (err, data) => {
t.error(err)
t.equal(data, 'hello world\nsomething else\n')
})
})
stream.on('close', () => {
t.pass('close emitted')
})
})

0 comments on commit 31cae66

Please sign in to comment.