learning nodejs

It is a good resource to learn nodejs

http://www.nodebeginner.org/

It is a pity that it only provides 19 pages to read for free.

It gives a good example to run nodejs and explain. You could download the nodejs for windows and then run in promote terminal, then follow the instructions, you  could see the result on the browser.

Building the application stack

A basic HTTP server

When I arrived at the point where I wanted to start with my first “real” Node.js application, I wondered not only how to actually code it, but also how to organize my code.
Do I need to have everything in one file? Most tutorials on the web that teach you how to write a basic HTTP server in Node.js have all the logic in one place. What if I want to make sure that my code stays readable the more stuff I implement?

Turns out, it’s relatively easy to keep the different concerns of your code separated, by putting them in modules.

This allows you to have a clean main file, which you execute with Node.js, and clean modules that can be used by the main file and among each other.

So, let’s create a main file which we use to start our application, and a module file where our HTTP server code lives.

My impression is that it’s more or less a standard to name your main file index.js. It makes sense to put our server module into a file named server.js.

Let’s start with the server module. Create the file server.js in the root directory of your project, and fill it with the following code:

var http = require("http");

http.createServer(function(request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello World");
  response.end();
}).listen(8888);

That’s it! You just wrote a working HTTP server. Let’s prove it by running and testing it. First, execute your script with Node.js:

node server.js

Now, open your browser and point it at http://localhost:8888/. This should display a web page that says “Hello World”.

That’s quite interesting, isn’t it. How about talking about what’s going on here and leaving the question of how to organize our project for later? I promise we’ll get back to it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s