Skip to content

Commit 8f7883f

Browse files
committed
http: add optimized sendFile
1 parent af8ed02 commit 8f7883f

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

lib/_http_server.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ const {
8888
validateObject,
8989
} = require('internal/validators');
9090
const Buffer = require('buffer').Buffer;
91+
const { pipeline } = require('stream');
9192
const { setInterval, clearInterval } = require('timers');
9293
let debug = require('internal/util/debuglog').debuglog('http', (fn) => {
9394
debug = fn;
@@ -225,6 +226,30 @@ function ServerResponse(req) {
225226
ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype);
226227
ObjectSetPrototypeOf(ServerResponse, OutgoingMessage);
227228

229+
ServerResponse.prototype.sendFile = function(file, options, callback) {
230+
if (typeof options === 'function') {
231+
callback = options;
232+
options = null;
233+
}
234+
235+
validateObject(options, 'options', { nullable: true });
236+
validateCallback(callback, 'callback');
237+
238+
const { start, end, highWaterMark } = options ?? {};
239+
240+
let path
241+
let fd
242+
243+
if (file instanceof FileHandle || Number.isInteger(file)) {
244+
fd = file
245+
} else {
246+
path = file
247+
}
248+
249+
// TODO (perf): Optimize this...
250+
pipeline(fs.createReadStream(path, { fd, start, end, highWaterMark }), callback);
251+
};
252+
228253
ServerResponse.prototype._finish = function _finish() {
229254
if (this[kServerResponseStatistics] && hasObserver('http')) {
230255
stopPerf(this, kServerResponseStatistics, {

0 commit comments

Comments
 (0)