Open In App

Node response.writeHead() Method

Last Updated : 09 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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'}




Next Article

Similar Reads