Node response.writeHead() Method
Last Updated :
09 Oct, 2024
The response.writeHead() property is used to send a response header to the incoming request. It was introduced in Node.js v1.0 and is a part of the 'http' module. The status code represents a 3-digit HTTP status code (e.g., 404), and the headers parameter contains the response headers. Optionally, a human-readable statusMessage can be provided as the second argument.
When using response.setHeader(), headers set with it will merge with those passed to response.setHeader(), where the latter takes precedence. If response.writeHead() is called without prior use of response.setHeader(), it directly writes supplied headers to the network channel, bypassing internal caching. This can affect the expected result of response.getHeader(). For progressive header population with future retrieval and modification, prefer using response.setHeader().
In order to get a response and a proper result, we need to import ‘http’ module.
Syntax:
// Import Module
const http = require('http');
response.writeHead(statusCode[, statusMessage][, headers]);
Parameters: It accepts three parameters as mentioned above and described below:
- statusCode <number>: It accepts the status codes that are of number type.
- statusMessage <string>: It accepts any string that shows the status message.
- headers <Object>: It accepts any function, array, or string.
Return Value <http.ServerResponse>: It returns a reference to the ServerResponse, so that calls can be chained.
The response.writeHead()
method sets the status code and headers for the HTTP response in Node.js. To learn more about managing HTTP responses and building full-stack applications, the Full Stack Development with Node JS course provides detailed lessons on HTTP handling with Node.js
Explore this Express.js Response Complete Reference article to uncover detailed explanations, advanced usage examples, and expert tips for mastering its powerful methods, properties, and events. Enhance your Express.js applications with comprehensive insights into response handling, customization, and error management.
Example 1: The below example illustrates the use of response.writeHead() property in Node.js.
JavaScript
// Node.js program to demonstrate the
// response.writeHead() Method
// Importing http module
var http = require('http');
// Setting up PORT
const PORT = process.env.PORT || 3000;
// Creating http Server
var httpServer = http.createServer(
function (request, response) {
const body = 'hello world';
// Calling response.writeHead method
response.writeHead(200,
{
'Content-Length':
Buffer.byteLength(body),
'Content-Type':
'text/plain'
});
response.end(body);
});
// Listening to http Server
httpServer.listen(PORT,
() => {
console.log("Server is running at port 3000...");
});
Step to run index.js file using the following command:
node index.js
Console Output:
Server is running at port 3000...
Example 2: The below example illustrates the use of response.writeHead() property in Node.js.
JavaScript
// Node.js program to demonstrate the
// response.writeHead() Method
// Importing http module
var http = require('http');
// Setting up PORT
const PORT = process.env.PORT || 3000;
// Creating http Server
var httpServer = http.createServer(
function (request, response) {
// Setting up Headers
response.setHeader('Content-Type', 'text/html');
response.setHeader(
'Set-Cookie',
[
'type=ninja',
'language=javascript'
]);
response.setHeader('X-Foo', 'bar');
// Calling response.writeHead method
response.writeHead(200,
{
'Content-Type': 'text/plain'
});
// Getting the set Headers
const headers = response.getHeaders();
// Printing those headers
console.log(headers);
// Prints Output on the
// browser in response
response.end('ok');
});
// Listening to http Server
httpServer.listen(PORT, () => {
console.log(
"Server is running at port 3000...");
});
Step to run index.js file using the following command:
node index.js
Output:
Server is running at port 3000...
[Object: null prototype] {
'content-type': 'text/plain',
'set-cookie': [ 'type=ninja', 'language=javascript' ],
'x-foo': 'bar'}
Similar Reads
Node.js response.write() Method The response.write() (Added in v0.1.29) method is an inbuilt Application program Interface of the âhttpâ module which sends a chunk of the response body that is omitted when the request is a HEAD request. If this method is called and response.writeHead() has not been called, it will switch to implic
3 min read
Node response.setHeader() Method The response.setHeader() method in Node.js is used to set HTTP headers for a response. It allows you to define one or more headers for the HTTP response sent by the server. If a header with the same name already exists, its value will be replaced. Additionally, headers can be set as an array of valu
3 min read
Node.js v8.Serializer.writeHeader() Method The v8.Serializer.writeHeader() method is an inbuilt application programming interface of the v8.Serializer module, is used to write out a header, that contains the serialization format version. Syntax: v8.Serializer.writeHeader(); Parameters: This method does not have any parameters. Return Value:
1 min read
Node.js Stream writable.write() Method The writable.write() method is an inbuilt application programming interface of Stream module which is used to write some data to the Writable stream. The callback function is called once the data has been completely handled. Syntax: writable.write( chunk, encoding, callback) Parameters: This method
2 min read
Node.js Stream writable._write() Method The writable._write() method is an inbuilt application programming interface of Stream module which is used to implement a writable stream. The writable._write() method is affixed with an underscore as it is inside the class that defines it. Moreover, the user program must not call it directly. This
3 min read
Node.js fs.write() Method File-writing is an important aspect of programming. Every programming language has a well-defined file module that can be used to perform file operations. JavaScript and Node.js also have file module which provides various inbuilt methods for performing read, write, rename, delete and other operatio
4 min read