#
Generate HTML & Text Code
This tutorial explains to you how to generate HTML & text code.
The main Node.js main usage is to create servers. A server receives a request and after that will send back a response.
It is important for the browser (if the response is sent to the browser) the type of content it has to deal with.
For this purpose in the header of the response it is an attribute named Content-Type
.
In order to generate an HTML content you have to add in the header of the response the following:
'Content-Type': 'text/html'
In order to generate a Text content you have to add in the header of the response the following:
'Content-Type': 'text'
Here it is an example which generates an HTML content:
var http = require('http');
var urlAddr = require('url');
console.log('START Node.js application ...');
http.createServer(function (req, res) {
var var1 = urlAddr.parse(req.url, true);
var shortUrl = var1.pathname;
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The relative URL you enterd is: <br> <b>"+shortUrl+"</b>");
return res.end();
}).listen(8082);
The code above is put in generateHtml.js file and run:
Here it is the result in the browser ( the browser interpret the HTML tags):
Here it is an example which generates a text content:
var http = require('http');
var urlAddr = require('url');
console.log('START Node.js application ...');
http.createServer(function (req, res) {
var var1 = urlAddr.parse(req.url, true);
var shortUrl = var1.pathname;
res.writeHead(200, {'Content-Type': 'text'});
res.write("The relative URL you enterd is: <br> <b>"+shortUrl+"</b>");
return res.end();
}).listen(8082);
The code above is put in generateText.js file and run:
Here it is the result in the browser (the browser interpret the HTML tags as text):