Node.js Introductory Tutorials Learning notes sharing (1/8)

Source: Internet
Author: User
Tags file upload php script install node node server port number

What is Node.js

Node.js is a server-side JavaScript runtime environment that allows JavaScript code to run on the back end (out of the browser environment). Node.js has features such as non-blocking (non-blocking) and event-driven (Event-driven), which enables Web services like Apache and Nginx, allowing you to build JavaScript-based web apps.

To implement JavaScript code running in the background, the code needs to be interpreted and executed correctly. Node.js's theory is that it uses Google's V8 virtual machine (JavaScript execution environment used by Google's Chrome browser) to interpret and execute JavaScript code.

In addition, there are many useful modules along with the Node.js, which can simplify a lot of repetitive work, such as outputting strings to terminals. Therefore, Node.js is in fact both a run-time environment and a library.

about how to install Node.js, here is not to repeat, you can directly refer to the official installation guide. After the installation is complete, continue with the following.

The first Node.js application: "Hello World"

Open the editor to create a helloworld.js file that writes code to the STDOUT output "Hello World":

The code is as follows Copy Code

Console.log ("Hello World");

Save the file and execute it through Node.js:

Node Helloworld.js terminal will output Hello world.

The requirement of a node.js Web application instance

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

Application of different module analysis

· 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)
· When a request is received by the server and passed through routing, it needs to be processed, so we need the final request handler
· Routing should also be able to process post data and encapsulate the data in a more user-friendly format for delivery to the request processing program, requiring data processing functionality
· Not only do we have to deal with URL-related requests, but we also have to show the content, which means we need some view logic for the request handler 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

Using PHP, you will typically use an Apache HTTP server with the MOD_PHP5 module. From this perspective, the entire "Receive HTTP request and provide a Web page" requirement does not require PHP to process at all.

But for Node.js, the concept is completely different. When using Node.js, we not only implement an application, but also implement the entire HTTP server. In fact, our web applications and the corresponding Web servers are basically the same. It seems to be a lot of stuff, but it's no trouble for Node.js.

Start with the first part of the--HTTP server:

Building an application's module a basic HTTP server
In order to keep the code readable, the different functions of the code into different modules, so that code separation can be achieved. This approach allows you to have a clean Master file (main) that you can execute with Node.js, and you can have clean modules that can be invoked by the main file and other modules.

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

Start with the server module, create a file called Server.js in the root directory of the project, and write the following code:

  code is as follows copy 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);

/* can also be written in the following form

var http = require ("http");

Function ONrequest (request, Response) {
  Response.writehead ({"Content-type": "Text/plain"});
  Response.Write ("Hello World");
  Response.End ();
}

Http.createserver (onrequest). Listen (8888);

* * So you can build a working HTTP server. To prove this, let's run and test this code. First, execute your script with Node.js:

Node Server.js Next, open your browser to visit http://localhost:8888/, and you'll see a Web page that says Hello world.

Analyzing HTTP Servers

Next, analyze the composition of this HTTP server.

The first line request (require) Node.js the self-contained HTTP module and assigns it to the HTTP variable.

Next we call 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 to.

You could have used such code to start the server and listen on port 8888:

The code is as follows Copy Code
var http = require ("http");
var server = Http.createserver ();
Server.listen (8888);

This code will only start a server that listens on port 8888, it does nothing else, and even requests do not answer.

Event-driven callbacks

When using the Http.createserver method, not only do you want a server that listens on a port, but we also want it to do something when the server receives an HTTP request.

The problem is that this is asynchronous: The request can be reached at any time, but the server runs in a single process.

When writing PHP apps, we don't worry about it at all: whenever a request comes in, the Web server (usually Apache) creates a new process for the request and starts executing the corresponding PHP script from start to finish. So in our Node.js program, how do we control the process when a new request arrives at Port 8888?

This is where Node.js/javascript's event-driven design can really help-though we have to learn some new concepts to master it.

Let's take a look at how these concepts are applied in our server code:

We created the server and passed a function to the method that created it. Whenever our server receives a request, this function is invoked. We don't know when this is going to happen, but we now have a place to process the request: It is the function that we pass past. It doesn't matter whether it's a predefined function or an anonymous function. This is the callback. We pass a function to a method that calls this function to invoke a callback when a corresponding event occurs.

Let us ponder over this new concept again. How do we prove that our code continues to work after the server is created, even if no HTTP requests come in and our callback functions are not invoked? Let's try this:

  code is as follows copy code

var http = Require ("http");

Function ONrequest (request, Response) {
  Console.log ("request received.");
  Response.writehead ({"Content-type": "Text/plain"});
  Response.Write ("Hello World");
  Response.End ();
}

Http.createserver (onrequest). Listen (8888);

Console.log ("Server has started.");

Note: where ONrequest (our callback function) triggers, I output a paragraph of text with Console.log. After the HTTP server has started working, a piece of text is also exported.
When we run the node server.js as usual, it will immediately output "server has started." On the command line. When we make a request to the server (in the browser to access http://localhost:8888/), "request received." This message will appear on the command line. This is the event-driven asynchronous server-side JavaScript and its callback. (Note that when we visit a Web page on the server, our server may output two times "Request received."). That's because most servers try to read Http://localhost:8888/favicon.ico when you access http://localhost:8888/


how the server handles requests
Next, let's briefly analyze the rest of the server code, which is the main part of our callback function ONrequest ().

When the callback is started, when our onrequest () function is triggered, two parameters are passed in: request and response. They are objects that you can use to handle the details of HTTP requests and respond to requests (such as sending back something to the requesting browser).

So our code is: When the request is received, use the Response.writehead () function to send a content type (content-type) of HTTP State 200 and HTTP headers, using the Response.Write () The function sends the text "Hello World" to the HTTP corresponding body.

Finally, we call Response.End () to complete the response. For now, we don't care about the details of the request, so we're not using a request object.

Where is the module on the server?
There is a very basic HTTP server code in the Server.js file, and the Index.js file calls the other modules of the application (such as the HTTP Server module in server.js) to boot and launch the application. How to turn server.js into a real node.js module? So that it can be used by the Index.js master file.

Perhaps you've noticed that we've used modules in our code:

The code is as follows Copy Code

var http = require ("http");

...

Http.createserver (...);

Node.js has a module called "http", which we request in code and assign the return value to a local variable. This turns the local variable into an object that owns the public methods provided by all HTTP modules.

It is a common practice to give this local variable a name that is the same as the module name, but you can also follow your own preferences:

The code is as follows Copy Code

var foo = require ("http");

...

Foo.createserver (...);

How to use the Node.js internal module is already very clear, how to create your own module, how to use it?

In fact, we don't have to make too many changes. Turning a piece of code into a module means we need to export the part of the function that we want to provide to the script that requested the module.

At present, our HTTP server needs to export the function is very simple, because the Request Server module script is only need to start the server.

We put the server script in a function called start, and then we export the function.

The code is as follows Copy Code

var http = require ("http");

function Start () {
function onrequest (request, Response) {
Console.log ("Request received.");
Response.writehead ({"Content-type": "Text/plain"});
Response.Write ("Hello World");
Response.End ();
}

Http.createserver (ONrequest). Listen (8888);
Console.log ("Server has started.");
}

Exports.start = start; Although the server's code is still in Server.js, it is now possible to create our main file Index.js and start http in it.

Create the Index.js file and write the following:

The code is as follows Copy Code

var server = require ("./server");

Server.start () We can use the server module like any other built-in module: request the file and point it to a variable, where the exported function can be used by us.

Now we can start our application from our main script:

Node Index.js can now put different parts of the application into different files and connect them to each other by generating modules.

We still only have the first part of the entire application: we can receive HTTP requests. But we have to do something--for different URL requests, the server should have a different response.

For a very simple application, you can do this directly in the callback function ONrequest (). But as I said, we should add some abstract elements to make our example more interesting.

Processing different HTTP requests is a different part of our code, called "Routing"--then we'll create a module called routing.

home 1 2 3 4 5 6 7 8 last

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.