URL Redirection Using Node.js

Lets learn how to redirect with a 301 status code – which means “moved permanently”, using Node.js

301-redirection

Related Read: HTTP Server(request/response): Node.js

Here we’re passing 301 redirect status code with redirection location URL in the header information to the client – the browser.

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
var http= require("http");
 
     http.createServer(function(req, res){
     res.writeHead(301, {
 "location" : "http://technotip.org"
 });
 res.end();
   }).listen(3030, "127.0.0.1");
 
 console.log("server redirects from localhost to technotip.org");

We require/include http module of node.js We call createServer() method of http object and this method passes 2 objects to the callback methodrequest and response objects. Using request object we call writeHead() method and pass 301 status code and the redirect location information. After this, we indicate the end of the process by calling end() method.

Also we assign the port 3030 at 127.0.0.1 for the client access of this server.

Now visit localhost:3030 or 127.0.0.1:300 and you’ll be redirected to http://technotip.org

301 Redirection Using Node.js


[youtube https://www.youtube.com/watch?v=neIeFVMsuJY]

YouTube Link: https://www.youtube.com/watch?v=neIeFVMsuJY [Watch the Video In Full Screen.]



Status Code Definitions

Informational 1xx
100 Continue
101 Switching Protocols

Successful 2xx
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content

Redirection 3xx
300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
306 (Unused)
307 Temporary Redirect

Client Error 4xx
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed

Server Error 5xx
500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

Network I/O Is Unpredictable: Node.js

We’ve seen the importance of callback method in our previous video tutorials. Now lets see how networked I/O Is unpredictable.


http-module-get-method-nodejs-network-io-unpredictability

Here we request/ping for information from 3 different servers and look at its response time. Each time we send a request, we get different response time depending upon how busy the server is, its bandwidth etc.

JavaScript File
app.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var http= require("http"),
      urls  = [ "technotip.org",
         "technotip.com",
      "www.capturecaption.com"
       ];
 
for(var i = 0; i < urls.length; i++){
ping( urls[i] );
}
 
function ping( url ){
var start = new Date();
 
http.get({ host: url }, function(res){
console.log("URL :"+url);
console.log("Response Time: "+(new Date() - start)+" ms");
});
}

Here we require http module, which is built into nodejs, and store it inside a local object called http. We also declare and initialize an array with 3 domain names. Using for loop, we loop through each URL present in the urls array and pass it to a method called ping();

Inside ping method, we record client system date in a variable before sending a request to the server(via URL). Now using http objects get method we send request to the server and see it’s response time. get method takes 2 parameter, first parameter is an object which contains host information – the host url { host: url }. Second parameter is a callback method which automatically gets an object which is returned by first parameter {host: url}. Inside the callback method, we subtract the new system date with the one we recorded before requesting for a response, this way we calculate the response time of each URL.

HTTP get method: Node.js


[youtube https://www.youtube.com/watch?v=vktKMtWoPbA]

YouTube Link: https://www.youtube.com/watch?v=vktKMtWoPbA [Watch the Video In Full Screen.]



output
C:\node>node app.js
URL :technotip.com
Response Time: 1462 ms
URL :www.capturecaption.com
Response Time: 1993 ms
URL :technotip.org
Response Time: 2004 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1381 ms
URL :www.capturecaption.com
Response Time: 1702 ms
URL :technotip.org
Response Time: 1871 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1409 ms
URL :www.capturecaption.com
Response Time: 1628 ms
URL :technotip.org
Response Time: 2001 ms

C:\node>node app.js
URL :technotip.com
Response Time: 1512 ms
URL :www.capturecaption.com
Response Time: 1534 ms
URL :technotip.org
Response Time: 1899 ms

Each time we execute the script, we get different response time, and the order of URLs may also differ, as we can’t predict which server will respond first.

Node.js Video Tutorial List

Stay subscribed. We will keep updating this page whenever we have a new video tutorial on nodejs

nodejs Getting Started: Node.js

..stay subscribed. These email subscriptions are free

Enter your email address:

Node.js Free Video Tutorials

  1. Getting Started: Node.js
  2. callback methods / anonymous functions: jQuery
  3. HTTP Server(request/response): Node.js
  4. HTTP Server(request/response) Counter Application: Node.js
  5. User Input Using readline Module: Node.js
  6. Local Module: Node.js
  7. External Module( NPM ) Install, Update, Remove: Node.js
  8. Network I/O Is Unpredictable: Node.js
  9. URL Redirection Using Node.js
  10. Read Evaluate Print Loop (RELP): Node.js
  11. Adding Routes to Your Server: Node.js
  12. Create/Read/Write File using File Server: Node.js
  13. Server Up or Down: Node.js
  14. Express Web Framework: Node.js
  15. Auto Restart Server With NoDemon: Node.js
  16. Basics of Jade – Template Engine: Node.js
  17. Loops and Conditions In Jade: Node.js
  18. Mixins in Jade: Node.js
  19. Forms Using Jade: Node.js
  20. Configuration of Express Application: Node.js
  21. Basic Routing Using Express: Node.js
  22. Advanced Routing Using Express: Node.js
  23. Middleware In Express: Node.js
  24. Cookies In Express: Node.js
  25. Sessions In Express: Node.js
  26. Error Handling In Express: Node.js
  27. Validating User Request: Node.js
  28. Connecting To MongoDB Using Mongoose: Node.js
  29. Save data To MongoDB: Node.js
  30. Fetch Data From MongoDB: Node.js
  31. Fetch Individual User Data From MongoDB: Node.js
  32. Update / Edit Data In MongoDB: Node.js
  33. Remove / Delete Data From MongoDB: Node.js

External Module( NPM ) Install, Update, Remove: Node.js

This video tutorial illustrates searching, installing, updating and removing the external, free modules.

External Free Node Modules are listed at npmjs.org and is managed by NPMNode Package Manager.

There are so many amazing modules already written to handle so many sophisticated functionalities, that it becomes easy to use them in our application and build a robust, scalable application quickly.

Command to look at all the external module names and their respective description

1
npm search

It gives a long list of names and descriptions.

To make is look better, you can use GREP(if you’re on Linux or Unix based System)
Search with GREP

1
npm search | grep module_name

npm search followed by pipe symbol, which is followed by any module name.

For Windows users

1
npm search module_name

it gives all the details of available methods, properties and their description.

Installation of Modules

init command

1
npm init

Once you run this command, it prompts you with some optional things, like, name of the project, version, author, licensing etc. Once you’re done with that, it creates package.json file with all the details you provided.

The ‘init’ command in NPM allows us to identify our project and list out any Node Modules it requires.

Now open that package.json file: it looks somewhat like this
package.json file

1
2
3
4
5
6
7
8
9
10
11
12
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

You need to open this package.json file using a plain text editor and add your project dependencies i.e., some of the modules you need to install for your project.

In this video tutorial we’re installing 3 external modules:
express
jade
mongoose

package.json file, after editing

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "name": "app",
  "version": "0.0.0",
  "description": "authentication application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
 "dependencies": { "express": "2.5.8", "jade": "0.26.1", "mongoose": "2.6.5" },
  "repository": "",
  "author": "SATISH B",
  "license": "BSD"
}

Now you’ve specified all the external modules your project depends on.

Now using install command, we need to install these modules.
installation command

1
npm install

Once this command is executed, it looks through the package.json file and installs all the dependency modules one by one.

External Module Install, Update, Remove via NPM: Node.js


[youtube https://www.youtube.com/watch?v=HRISSD0ic2s]

YouTube Link: https://www.youtube.com/watch?v=HRISSD0ic2s [Watch the Video In Full Screen.]



What is a module?
A module is a self-contained series of one or more javascript files represented by an object.

Update Command

1
npm update

once you run this command, package.json file is parsed and the dependency modules are checked for any updates, if any, it’ll be updated.
If any module is installed with -g (global scope), i.e., the root installation, then while updating or removing them, it may throw some errors, in such case, use sudo keyword:

Update Command

1
sudo npm update -g

This would solve the problem both for updating and deleting external modules.

remove/delete module command

1
npm prune

To remove the unused modules: open package.json file and remove the module names which you want to remove. Save the package.json file and then run above(npm prune) command. This would safely remove the modules you no more intend to use in your project.

List Global module: using command

1
npm -g ls

This lists all the global modules, it’s path and file structure: as shown below:

Example output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
C:\node\express_example>npm  -g ls
C:\Users\Satish\AppData\Roaming\npm
└─┬ [email protected]
  ├── [email protected]
  ├─┬ [email protected]
  │ └── [email protected]
  ├─┬ [email protected]
  │ ├── [email protected]
  │ ├─┬ [email protected]
  │ │ ├── [email protected]
  │ │ └── [email protected]
  │ ├── [email protected]
  │ ├── [email protected]
  │ └── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  ├── [email protected]
  └─┬ [email protected]
    └── [email protected]

Removing/Uninstalling Global modules: using command

1
npm -g rm

This removes all the global modules installed.

Clear cache

1
npm cache clear

After modifiying things from command prompt, if it’s still not working, try clearing the cache.

Note:
To install latest version of the module: you’ll need to write * (asterisk or star) in the place of version number inside package.json file.

Local Module: Node.js

In this video tutorial we shall see how to write and make use of local modules in Node.js application.

In previous video tutorials we’ve seen the procedure for writing and using built-in Node.js modules.
HTTP module.
readline Module.

This is a simple tutorial to demonstrate writing of local module

Local Module File
students.js

1
exports.students = [ 'Satish', 'Kiran', 'Sunitha', 'Jyothi' ];

exports is a global provided by node.js
students is a name given by us; it’s a property name and we assign an array to it which contains some names.

Application File
appStu.js

1
2
3
var students = require('./students');
 
console.log(students.students);

We require the local module students in appStu.js file.
./ (dot followed by a forward slash) specifies that it’s a local module and it need not search for the file in core module or node module collection.

Next, object.property name will print out the entire array present inside the local module file.

Local Module: Node.js


[youtube https://www.youtube.com/watch?v=qh2e_9AmakI]

YouTube Link: https://www.youtube.com/watch?v=qh2e_9AmakI [Watch the Video In Full Screen.]



Note:
One of the main advantages of local modules is, the reusability of code. It also helps in separating specific logic and keeping the code clean.