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");
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 method – request 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
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
We’ve seen the importance of callback method in our previous video tutorials. Now lets see how networked I/O Is unpredictable.
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");
});
}
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.
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.
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 NPM – Node 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
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 | grep module_name
npm search followed by pipe symbol, which is followed by any module name.
For Windows users
1
npm search module_name
npm search module_name
it gives all the details of available methods, properties and their description.
Installation of Modules
init command
1
npm init
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
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
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
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
sudo npm update -g
This would solve the problem both for updating and deleting external modules.
remove/delete module command
1
npm prune
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
npm -g ls
This lists all the global modules, it’s path and file structure: as shown below:
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);
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.