Home » Node.js25 July 2017

Node.js: Basic Routing [Beginner Tutorial]

This article shows how you can create a basic HTTP routing in Node.js.

In the example code, we will be using two built-in Node.js modules: http module and fs module. To create HTTP server, we need http module. And, to read/write file data, we need to use fs module.

We will create an http server and write if/else conditions to read HTML files according to routing parameter.

To read HTML files, we use fs.createReadStream() function. createReadStream reads file in chunks of specified size. It’s better than using fs.readFile() function which loads the entire file into memory before processing.

With createReadStream, we use pipe() event which helps in writing response data to browser.

Let’s first create 3 html files: index.html, about.html, contact.html

index.html

about.html

contact.html

Now, here’s our Nodejs file that creates server and does the routing. Let’s name it main.js.

main.js

Now, open terminal/command-prompt and go to the directory where your main.js file is. My main.js file is at /var/www/html/test/nodejs/main.js.

After you are in the directory where the above created main.js file is, then run the following command:

This will print the message in your terminal/command-prompt saying “Server running at port 8081…” like below:

Now, open your browser and type the following in your browser’s address bar:

http://127.0.0.1:8081

Press Enter and you shall be able to see content of index.html file loaded on your browser.

http://127.0.0.1:8081/about will show content of about.html file.
http://127.0.0.1:8081/contact will show content of contact.html file.

Any other parameters in the URL will show content of index.html file. For example,
http://127.0.0.1:8081/xyz will show content of index.html file.

That’s it! You have successfully created a basic HTTP routing in Node.js.

Hope this helps. Thanks.

Node.js

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed