DunDev
DunDev

Reputation: 210

What will happen if I remove res.end() when creating a server in NodeJS?

I'm learning to create a simple server with NodeJS. Here is the code I extracted from my material:

var http = require('http');
var server = http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end();
});

server.listen(3000);

What does res.end() do in this example? Must I use res.end() everytime I create a server? What will happen behind if I remove res.end() from the code above?

(I've tried removing res.end() from the code, run it, and what I see was the browser kept loading continously without showing anything (even the white blank page). I have no ideas what is happening behind)

Any help is appreciated!

Upvotes: 0

Views: 1977

Answers (2)

Vipin Kumar
Vipin Kumar

Reputation: 6546

First let's break your code line by line

var http = require('http');

This is to import http library from node.js in built libraries. Which can be used to do http related tasks. Creating server is one of that task.

var server = http.createServer(fn).
server.listen(3000);

server.listen(3000) will start a http server which will listen for http requests coming at localhost:3000. Each time your hit this address in your browser, fn function will be executed. No matter what route you hit. fn will be executed for localhost:3000 as well as for localhost:3000/anything/else

function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end();
}

When this function is executed when you hit localhost:3000 in your browser, two objects request(req) and response(res) are suppled to this function via http library. req contains all the data related to request like URL, Body, etc. Response contains methods that you can use to build your response that is passed to the client or browser (who have initiated the request).

res.writeHead(200, {'Content-Type': 'text/plain'});
res.end();

Here first, header is written into response then it is notified to http via res.end() that we have finished writing the response, please send it to the client. Please note, once you have end writing the response, you can write anything else in your response.

Regarding removing the res.end() you have already answered your question that browser kept loading. In actual, browser is waiting for a response from the server. If you will remove res.end(), server will not be able to notify client that response writing is done.

Upvotes: 3

Crappy
Crappy

Reputation: 451

res.send()

Is sending a response to the client. If you are not sending a response back to the client you will not recieve any answer to render in your browser.

You have to send a response to the client from every route you specify. In your example the function you are passing to the createServer() method gets executed when the root address of your server is called. If you run this locally this would be localhost:3000

Upvotes: 1

Related Questions