Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,13 @@ Serve files relative to `path`.
Byte offset at which the stream starts, defaults to 0. The start is inclusive,
meaning `start: 2` will include the 3rd byte in the stream.

##### autoEnd

Enable or disable ending the stream of the http response after pipe, defaults to true.
Disabling this will ignore the header `Content-Length` which will force
the `Transfer-Encoding` to be `chunked`. User can listen the event `end`
for further operation. Here is the doc about [pipe]('https://nodejs.org/dist/latest-v6.x/docs/api/stream.html#stream_readable_pipe_destination_options').

#### Events

The `SendStream` is an event emitter and will emit the following events:
Expand Down
7 changes: 5 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,9 @@ SendStream.prototype.send = function send (path, stat) {
opts.end = Math.max(offset, offset + len - 1)

// content-length
res.setHeader('Content-Length', len)
if (options.autoEnd !== undefined ? options.autoEnd : true) {
res.setHeader('Content-Length', len)
}

// HEAD support
if (req.method === 'HEAD') {
Expand Down Expand Up @@ -803,7 +805,8 @@ SendStream.prototype.stream = function stream (path, options) {
// pipe
var stream = fs.createReadStream(path, options)
this.emit('stream', stream)
stream.pipe(res)
var autoEnd = options.autoEnd !== undefined ? options.autoEnd : true
stream.pipe(res, {end: autoEnd})

// response finished, done with the fd
onFinished(res, function onfinished () {
Expand Down
24 changes: 24 additions & 0 deletions test/send.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ var app = http.createServer(function (req, res) {
.pipe(res)
})

var appPipeNotEnd = http.createServer(function (req, res) {
function error (err) {
res.statusCode = err.status
res.end(http.STATUS_CODES[err.status])
}

function end () {
res.end('tobi')
}

send(req, req.url, {root: fixtures, autoEnd: false, acceptRanges: false})
.on('error', error)
.on('end', end)
.pipe(res)
})

describe('send(file).pipe(res)', function () {
it('should stream the file contents', function (done) {
request(app)
Expand Down Expand Up @@ -1420,6 +1436,14 @@ describe('send.mime', function () {
})
})

describe('send(file).pipe(res,false)', function () {
it('should stream the file contents with append', function (done) {
request(appPipeNotEnd)
.get('/name.txt')
.expect(200, 'tobitobi', done)
})
})

function createServer (opts, fn) {
return http.createServer(function onRequest (req, res) {
try {
Expand Down