Nodejs url module
[php]var url = require(‘url’);[/php]
The url.parse() method parses a URL address and then returns a specific address object
[php]
var url = require(‘url’);
var adr
= ‘http://localhost:8080/default.htm?year=2017&month=february’;
var q = url.parse(adr, true);
console.log(q.host); //returns
‘localhost:8080’
console.log(q.pathname); //returns
‘/default.htm’
console.log(q.search); //returns
‘?year=2017&month=february’
var qdata = q.query; //returns an object: { year: 2017,
month: ‘february’ }
console.log(qdata.month); //returns ‘february’
[/php]
Node.js file server
Now we know how to parse a query string, and in the previous chapter we learned how to make Node.js act as a file server. Let’s combine the two to serve the file requested by the client. Create an HTML file in the same folder as your js file and save it
Now we create 2 files in the same directory
summer.html
[php]
<!DOCTYPE html>
<html>
<body>
<h1>Summer</h1>
<p>I love the sun!</p>
</body>
</html>
[/php]
winter.html
[php]
<!DOCTYPE html>
<html>
<body>
<h1>Winter</h1>
<p>I love the snow!</p>
</body>
</html>
[/php]
Then create a node.js file in the same folder
[php]
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);
[/php]
Then execute the file
[php]
node node.js
[/php]
If you enter http://localhost:8080/summer.html
it will automatically locate it and return the contents of summer.html
If you enter http://localhost:8080/winter.html, it will automatically locate it and return
the contents of winter.html
If you enter any other characters, it will return 404