Example url module in nodejs

Example: Split a web address into readable parts

 

var url = require('url');

var adr = 'http://localhost:8080/index.htm?year=2018&month=february';

var q = url.parse(adr, true);

console.log(q.host); //returns 'localhost:8080'

console.log(q.pathname); //returns '/index.htm'

console.log(q.search); //returns '?year=2018&month=february'

var qdata = q.query; //returns an object: { year: 2018, month: 'february' }

console.log(qdata.month); //returns 'february'

console.log(qdata.year); //returns '2018'

 

Run program via cmd:

 

C:\Nodejs>node urlModule.js

 

Output:

 

localhost:8080

/index.htm

?year=2018&month=february

february

2018

 

Example 2 : create webserver with nodejs

Create two html files and save them in the same folder as your node.js files.

Index.html

 

<html>

<body>

<h1>Home</h1>

<p>Welcome to my page</p>

</body>

</html>

 

Contact.html

 

<html>

<body>

<h1>Contact</h1>

<p>Please contact with me</p>

</body>

</html>

 

webserver.js

 

var http = require('http');

var url = require('url');

var fs = require('fs');

http.createServer(function (req, res) {

  var q = url.parse(req.url, true);

  var filename = "." + q.pathname;

  fs.readFile(filename, function(err, data) {

    if (err) {

      res.writeHead(404, {'Content-Type': 'text/html'});

      return res.end("404 Not Found");

    } 

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

    res.write(data);

    return res.end();

  });

}).listen(8080);

 

Run program via cmd:

 

C:\Nodejs>node webServer.js

 

Go browser

http://localhost:8080/index.html

 

Home

Welcome to my page

 

http://localhost:8080/contact.html

 

Contact

Please contact with me