How to create URL in NodeJS?

NodeJs

Nodejs is an open-source, cross-platform JavaScript framework. Due to its single threaded in nature it is used for modern websites development, backend API services, real-time applications, event-driven servers etc. When we are creating websites using Nodejs then we needs to access our webpages through URLs. And we can do this using the URL module, HTTP module and FS module. So, in this tutorial we will learn how to create URL in NodeJS.

Modules in NodeJS

HTTP Module – To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP.

URL Module – URL module is one of the core modules that comes with node.js, which is used to parse the URL and its other properties.

FS Module – The Node.js file system module allows you to work with the file system on your computer like create a file, open a file, read a file, edit a file, delete a file.

Access Webpage through URL in NodeJS

Step 1 : Create a file server.js in your project directory and paste the code given below

/*modules*/
var http = require('http');
var fs = require('fs');
var url = require('url');
/*modules*/

/*create server*/

http.createServer(function(request, response){

	var pathname = url.parse(request.url).pathname;

	fs.readFile(pathname.substr(1), function(err, data){

		if (err) {
			response.writeHeader(404,{'Content-Type': 'text/html'});
		}else{

			response.writeHeader(200,{'Content-Type': 'text/html'});
			response.write(data.toString());

		}

		response.end();


	});

}).listen(8100);

console.log('Server is running at http://localhost:8100');

/* If production server then localhost can be replaced with your server IP or domain name */

/*create server*/

Step 2 : Run this command through your command prompt or terminal.

node server.js

Now, your server will run at PORT 8100 and URL will be http://localhost:8100 if local machine, else will be your live URL.

Step 3 : Create html file which you want to access through URL. For example, if your URL is http://localhost:8100/home.html. Then create a file home.html in your project directory.

That’s it, Now you can create URL in NodeJS.

Recommended:

How to use events in Node.js

How to upload file in Node.js

Create REST API in Node.js

Create URL in Node.js

For more NodeJS Tutorials visit NodeJS page.

If you like this, share this.

Follow us on FacebookTwitterTumblrLinkedInYouTube