Node.js Tutorial – 2


Previous Tutorial on nodejs can be found at [1].

The nodejs executable allows you to set up a webserver quickly and easily via Javascript, for example, the following illustrates the idea. Using node to execute the javascript, and you will find out the server has started, a process is launched, running, listening to port 8080 without returning to the command line.

nodejs5 Node.js Tutorial – 2 http I/O File internet javascript network nodejs programming languages

require function is similar to import keyword in Java, include in C/C++, which allows you to include/import another package/file. The http package is required to create a web server.

http.createServer, as the name implies, is used to create a server, which takes a parameter as a function that specifies the request and response objects. The rest are easy to understand, response can write to output via write, and sends the 200 (meaning status OK), via writeHead.

http.createServer returns the server object, which you can use listen function to specify a port for which the server listens to, for the connections.

The parameter can be specified as a function var, for example,

1
2
3
4
5
6
7
8
9
var http = require("http");
 
var server = function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write((function(name){return "Hello, " + name;})("justyy"));
    response.end();  
}
 
http.createServer(server).listen(8080);
var http = require("http");

var server = function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write((function(name){return "Hello, " + name;})("justyy"));
    response.end();  
}

http.createServer(server).listen(8080);

The above code produces the same effects, but in a clearer manner.  The nice thing about nodejs is that you don’t need to install server such as Apache, IIS in order to access http://localhost

nodejs4 Node.js Tutorial – 2 http I/O File internet javascript network nodejs programming languages

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
389 words
Last Post: Node.js Tutorial - 1
Next Post: Codeforces: 268B. Buttons

The Permanent URL is: Node.js Tutorial – 2

Leave a Reply