See this example from Node.js docs:
response.writeHead(statusCode[, statusMessage][, headers])
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain',
})
.end(body);
The second parameter of writeHead
function should be statusMessage
.
Why can this second parameter be skipped automatically, don’t we need a undefined or null for the parameter? How does Node.js know the object is for the third parameter?
Why not:
const body = 'hello world';
response
.writeHead(200, undefined, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain',
})
.end(body);
New contributor
The documentation says:
The last argument, headers, are the response headers. Optionally one can give a human-readable statusMessage as the second argument.
The implementation of the writeHead
function checks whether the second argument is string
or object
and behaves accordingly. You can see it in the source.
if (typeof reason === 'string') {
// writeHead(statusCode, reasonPhrase[, headers])
// ...
} else {
// writeHead(statusCode[, headers])
// ...
}