diff --git a/src/core/write.js b/src/core/write.js index 357d898573..2c0c237322 100644 --- a/src/core/write.js +++ b/src/core/write.js @@ -128,7 +128,7 @@ const write = async (context, source, destination, options) => { // pad start of file if necessary if (options.offset > 0) { - if (destination.unixfs && destination.unixfs.fileSize() > options.offset) { + if (destination.unixfs) { log(`Writing first ${options.offset} bytes of original file`) sources.push( @@ -139,6 +139,15 @@ const write = async (context, source, destination, options) => { }) } ) + + if (destination.unixfs.fileSize() < options.offset) { + const extra = options.offset - destination.unixfs.fileSize() + + log(`Writing zeros for extra ${extra} bytes`) + sources.push( + asyncZeroes(extra) + ) + } } else { log(`Writing zeros for first ${options.offset} bytes`) sources.push( diff --git a/test/core/write.js b/test/core/write.js index b0df007ea5..c0c0588f71 100644 --- a/test/core/write.js +++ b/test/core/write.js @@ -373,11 +373,13 @@ describe('write', () => { const stats = await mfs.stat(path) expect(stats.size).to.equal(newContent.length + offset) - const buffer = Buffer.concat(await all(mfs.read(path, { - offset: offset - 5 - }))) + const buffer = Buffer.concat(await all(mfs.read(path))) + + if (content[Symbol.asyncIterator]) { + content = Buffer.concat(await all(content)) + } - expect(buffer).to.deep.equal(Buffer.concat([Buffer.from([0, 0, 0, 0, 0]), newContent])) + expect(buffer).to.deep.equal(Buffer.concat([content, Buffer.from([0, 0, 0, 0, 0]), newContent])) }) })