Node.js routing using url module
Today we are going to learn how to use url node.js module to route Node.js application..We are going to use url.parse method to get the pathname,find the file and read it using fs.readFile method.Save the data and write is using write() method.
write below file and save it in the same folder containing index.js file.
webpage.html
<!DOCTYPE html>
<html>
<body>
<h1>File number 2</h1>
<p>This is the first file that will be loaded by Node.js</p>
</body>
</html>
webpage2.html
<!DOCTYPE html>
<html>
<body>
<h1>File number 2</h1>
<p>This is the second file that will be loaded by Node.js</p>
</body>
</html>
write node.js file and save it index.js
var http=require('http');
var fs=require('fs');
var url=require('url');
http.createServer(function(req,res)
{
var query=url.parse(req.url,true);
var filename='.' + query.pathname;
fs.readFile(filename,function(err,data)
{
if(err)
{
res.writeHead(404,{'Content-Type':'text/html'});
res.write("404 Not found error");
return res.end();
}
else
{
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
return res.end();
}
});
})
.listen(8080);
console.log('Server running');
Output.