Skip to content

Commit

Permalink
fix: call fs.createReadStream lazily (#2357)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbargiel committed Feb 26, 2024
1 parent 81c20dd commit ba9fc42
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 12 deletions.
21 changes: 9 additions & 12 deletions lib/interceptor.js
Expand Up @@ -198,10 +198,16 @@ module.exports = class Interceptor {
if (!fs) {
throw new Error('No fs')
}
const readStream = fs.createReadStream(filePath)
readStream.pause()
this.filePath = filePath
return this.reply(statusCode, readStream, headers)
return this.reply(
statusCode,
() => {
const readStream = fs.createReadStream(filePath)
readStream.pause()
return readStream
},
headers,
)
}

// Also match request headers
Expand Down Expand Up @@ -453,15 +459,6 @@ module.exports = class Interceptor {
markConsumed() {
this.interceptionCounter++

if (
(this.scope.shouldPersist() || this.counter > 0) &&
this.interceptionCounter > 1 &&
this.filePath
) {
this.body = fs.createReadStream(this.filePath)
this.body.pause()
}

remove(this)

if (!this.scope.shouldPersist() && this.counter < 1) {
Expand Down
33 changes: 33 additions & 0 deletions tests/got/test_reply_with_file.js
Expand Up @@ -64,6 +64,29 @@ describe('`replyWithFile()`', () => {
scope.done()
})

it('reply with file with persist', async () => {
sinon.spy(fs)

const scope = nock('http://example.test')
.persist()
.get('/')
.replyWithFile(200, binaryFilePath, {
'content-encoding': 'gzip',
})

const response1 = await got('http://example.test/')
expect(response1.statusCode).to.equal(200)
expect(response1.body).to.have.lengthOf(20)

const response2 = await got('http://example.test/')
expect(response2.statusCode).to.equal(200)
expect(response2.body).to.have.lengthOf(20)

expect(fs.createReadStream.callCount).to.equal(2)

scope.done()
})

describe('with no fs', () => {
const { Scope } = proxyquire('../../lib/scope', {
'./interceptor': proxyquire('../../lib/interceptor', {
Expand All @@ -79,4 +102,14 @@ describe('`replyWithFile()`', () => {
).to.throw(Error, 'No fs')
})
})

it('does not create ReadStream eagerly', async () => {
sinon.spy(fs)

nock('http://example.test').get('/').replyWithFile(200, binaryFilePath, {
'content-encoding': 'gzip',
})

expect(fs.createReadStream.callCount).to.equal(0)
})
})

0 comments on commit ba9fc42

Please sign in to comment.