Start-up note-node.js a complete Web application based on node. js

Source: Internet
Author: User
Tags node server

Case

Let's set the goal to a simple point, but it's practical enough:

    • Users can use our app through a browser.
    • When the user requests Http://domain/start , you can see a welcome page with a file upload form on the page.
    • The user can select a picture and submit the form, and then the file will be uploaded to http://domain/upload, which will display the image on the page when the page is uploaded.

Almost, you can now go to Google, find something to mess around to complete the function. But we're not going to do this right now.

Further, in accomplishing this goal, we need more than just the underlying code, regardless of the elegance of the code. We also want to abstract this out to find a way to build more complex node. JS applications.

Application of different module analysis

Let's break down this application, what parts do we need to implement in order to implement the use case above?

    • We need to provide a Web page, so we need an HTTP server
    • For different requests, depending on the URL of the request, our server needs to give a different response, so we need a route to correspond the request to the request handler (requests handler)
    • After the request is received by the server and passed through the route, it needs to be able to process it, so we need the final request Handler
    • The route should also be able to process post data and encapsulate the data in a more friendly format to the request processing program, so request data processing functions
    • Not only do we have to deal with URL requests, we also show the content, which means we need some view logic for the request handler to use to send the content to the user's browser
    • Finally, the user needs to upload the image, so we need to upload the processing function to deal with this detail

Let's start by thinking about how we would build this structure using PHP. In general, we will use an Apache HTTP server with the MOD_PHP5 module.
From this perspective, the entire "Receive HTTP request and provide Web page" requirement does not need PHP to handle at all.

But for node. JS, the concept is completely different. When using node. js, we are not only implementing an application, but also implementing an entire HTTP server. In fact, our web application and the corresponding Web server are basically the same.

It sounds like there's a lot of work to be done, but then we'll gradually realize that it's not a hassle for node. js.

Now let's start with the implementation, starting with the first part of the--http server.

Building the application's module

A basic HTTP Server

When I was ready to start writing my first "real" node. js app, I didn't know how to write the node. JS code or how to organize it.
Should I put everything in a file? There are many tutorials on the web that will teach you to put all your logic into a basic HTTP server written in node. js. But what if I want to add more content and also want to keep the code readable?

In fact, it is fairly straightforward to keep the code separate as long as the code for different functions is put into different modules.

This method allows you to have a clean master file (main files) that you can execute with node. js, and you can have clean modules that can be called by the main file and other modules.

Now, let's create a master file to launch our app, and a module that holds our HTTP server code.

In my impression, the main file is called index.js more or less a standard format. Putting the server module in a file called Server.js is well understood.

Let's start with the server module first. Create a file called Server.js in the root directory of your project and write the following code:

Varhttp=Require("http");

http.Createserver(function (request, Response{
  Response. (200,{ " Content-type ":" Text/plain "});   Response. Write "Hello World"   Response. End }). listen8888

Get! You have just completed an HTTP server that can work. To prove this, let's run and test the code. First, execute your script with node. JS:

Node Server.js

Next, open the browser to access http://localhost:8888/, and you'll see a page with "Hello World".

It's funny, isn't it? Let's talk about the problem of HTTP server first, how do you think about how to organize the project? I promise that we will solve the problem after that.

Parsing an HTTP server

So let's look at the composition of this HTTP server next.

The first line requests (require)node. JS's own HTTP module and assigns it to the HTTP variable.

Next we invoke the function provided by the HTTP module: createserver . This function returns an object that has a method called Listen , which has a numeric parameter that specifies the port number that the HTTP server listens on.

Let's just ignore the function definition in http.createserver 's parentheses.

We could have used this code to start the server and listen on port 8888:

var= require("http");

var= http. Createserver();
Server. Listen(8888);

This code will only start a server listening on port 8888, it does nothing else, even the request will not answer.

The most interesting (and, if you used to use a more conservative language, such as PHP, it's strange) is the first parameter of createsever () , a function definition.

In fact, this function definition is the first and only parameter of createserver () . Because in JavaScript, functions can be passed in the same way as other variables.

Perform function passing

For example, you can do this:

functionSay (word) { 
  Console. Logword }

function Execute (somefunction, Value) {
  Somefunction (value
}

Execute ( Say, "Hello"

Please read this code carefully! Here, we pass the say function as the first variable of the execute function. The return value here is not say , but the say itself!

In this way, say becomes the local variable someFunction in execute , which can be called by SomeFunction () (in the form of parentheses) to use the say function.

Of course, because say has a variable, execute can pass such a variable when calling someFunction .

We can, as we just did, pass a function as a variable with its name. But we don't have to go around this "define first, then pass" circle, and we can define and pass the function directly in the parentheses of another function:

Function Execute(someFunction, value){
SomeFunction(value);
}

Execute(function(word) { console. Log(word)},"Hello");

We directly define the function we are going to pass to execute , where execute accepts the first argument.

In this way, we don't even have to name the function, which is why it is called an anonymous function .

This is the first time we have been in touch with what I think of as "advanced" javascript, but we have to step it up. Now, let's accept this: in JavaScript, one function can receive a parameter as another function. We can define a function first, then pass it, or we can define the function directly where the parameter is passed.

function passing is how to get the HTTP server to work

With this knowledge, let's take a look at our simple and not simple HTTP server:

Varhttp=Require("http");

http.Createserver(function (request, Response{
  Response. (200,{ " Content-type ":" Text/plain "});   Response. Write "Hello World"   Response. End }). listen8888

Now it should look a lot clearer: we passed an anonymous function to the createserver function.

This code can also be used to achieve the same purpose:

Varhttp=Require("http");

functionONrequest(Request,Response){
Responsewritehead (200,{ "Content-type" : "Text/plain" });   Response. Write "Hello World"   Response. End }

Http. Createserveronrequest8888

Maybe now we should ask this question: Why should we use this way?

Start-up note-node.js a complete Web application based on node. js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.