Node.js Creating HTTP Server using http.createServer()

Node.js Node.js Basic Node.js HTTP

Using Node.js built-in HTTP module to create a simple HTTP Server that return a text or HTML content when you access via browser.

Example 1 - Creating HTTP server to return a simple text content

var http = require('http');

var server = http.createServer();
server.on('request', function(req, res){
    res.writeHead(200, {'content-type': 'text/plain'});
    res.write('Welcome to toricode.com');
    res.end();
});

var port = 8080;
server.listen(port);
server.once('listening', function(){
    console.log('The HTTP server started and listening on port %d', port);
});

Save the code to server.js file and execute the code

D:\ToriCode\Nodejs>node server.js
The HTTP server started and listening on port 8080

The access the URL http://localhost:8080/ via your browser

Creating HTTP Server using http.createServer() with text response

Example 2 - Creating HTTP server to return a HTML content

var http = require('http');

var server = http.createServer();
server.on('request', function(req, res){
    res.writeHead(200, {'content-type': 'text/html'});
    res.write('<h1>Welcome to <u>toricode.com</u></h1>');
    res.end();
});

var port = 8080;
server.listen(port);
server.once('listening', function(){
    console.log('The HTTP server started and listening on port %d', port);
});

Save the code to server.js file and execute the code

D:\ToriCode\Nodejs>node server.js
The HTTP server started and listening on port 8080

The access the URL http://localhost:8080/ via your browser

Creating HTTP Server using http.createServer() with HTML response