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
25 changes: 23 additions & 2 deletions lib/response.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ res.links = function(links) {
* res.send({ some: 'json' });
* res.send('<p>some html</p>');
*
* @param {string|number|boolean|object|Buffer} body
* @param {string|number|boolean|object|Buffer|ArrayBuffer} body
* @public
*/

Expand Down Expand Up @@ -148,7 +148,11 @@ res.send = function send(body) {
case 'object':
if (chunk === null) {
chunk = '';
} else if (ArrayBuffer.isView(chunk)) {
} else if (ArrayBuffer.isView(chunk) || isArrayBuffer(chunk)) {
// `ArrayBuffer.isView()` is false for a raw ArrayBuffer, so its bytes
// are copied into a Buffer; otherwise it would fall through to
// `res.json()` below and be serialized as an empty object.
chunk = ArrayBuffer.isView(chunk) ? chunk : Buffer.from(chunk);
if (!this.get('Content-Type')) {
this.type('bin');
}
Expand Down Expand Up @@ -1011,6 +1015,23 @@ function sendfile(res, file, options, callback) {
file.pipe(res);
}

/**
* Determine if `obj` is a raw ArrayBuffer or SharedArrayBuffer.
*
* `ArrayBuffer.isView()` only detects views over a buffer (TypedArray and
* DataView), and `instanceof` is not reliable across realms, so the internal
* class of the object is checked instead.
*
* @param {*} obj
* @return {boolean}
* @private
*/

function isArrayBuffer (obj) {
var tag = Object.prototype.toString.call(obj);
return tag === '[object ArrayBuffer]' || tag === '[object SharedArrayBuffer]';
}

/**
* Stringify JSON, like JSON.stringify, but v8 optimized, with the
* ability to escape characters that can trigger HTML sniffing.
Expand Down
26 changes: 26 additions & 0 deletions test/res.send.js
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,32 @@ describe('res', function(){
})
})

describe('.send(ArrayBuffer)', function(){
it('should send as application/octet-stream', function(done){
var app = express();
app.use(function(req, res){
res.send(new TextEncoder().encode('hey').buffer);
});
request(app)
.get('/')
.expect(200)
.expect('Content-Type', 'application/octet-stream')
.expect(utils.shouldHaveBody(Buffer.from('hey')))
.end(done)
})

it('should not override an existing Content-Type', function(done){
var app = express();
app.use(function(req, res){
res.set('Content-Type', 'text/plain').send(new TextEncoder().encode('hey').buffer);
});
request(app)
.get('/')
.expect('Content-Type', 'text/plain; charset=utf-8')
.expect(200, 'hey', done);
})
})

describe('.send(Object)', function(){
it('should send as application/json', function(done){
var app = express();
Expand Down