Nodejs notes a complete Web application based on Node.js __js

Source: Internet
Author: User
Tags function definition install node node server
Author: Manuel Kiessling

Translation: Goddyzhao & Grayzhang & Mondaychen


about

This book is dedicated to teaching you how to use Node.js to develop applications that will impart all of the "advanced" javascript knowledge you need. This book is by no means a "Hello world" tutorial. State

What you are reading is already the final edition of this book. Therefore, updates are made only when error corrections are made and corresponding revisions are made to the new version node.js changes.

The code cases in this book have been tested in the Node.js version 0.6.11 and can work correctly. Reader Object

This book is best for readers with a similar technical background: at least a certain amount of experience in an object-oriented language such as Ruby, Python, PHP, or Java; JavaScript is a beginner and a node.js novice.

This refers to developers who have some experience with other programming languages, meaning that the book does not introduce very basic concepts such as data types, variables, control structures, and so on. To read this book, these basic concepts I have tacitly you already have.

However, the book also gives a detailed description of functions and objects in JavaScript because they are very different from functions and objects in other languages of the same programming language. the structure of the book

After reading this book, you will complete a complete Web application that allows users to browse the page and upload files.

Of course, the application itself is nothing great, but rather than the code itself to implement the feature, we are more concerned with creating a framework for cleanly stripping the different modules we apply. is not very iffy. You'll understand later.

This book begins by introducing the differences between JavaScript development in a node.js environment and JavaScript development in a browser environment.

Next, it will lead you to complete the most traditional "Hello World" application, which is also the most basic node.js application.

Finally, we will discuss how to design a "real" complete application, dissect the different modules that need to be implemented to complete the application, and explain how to implement these modules step-by-step.

To be sure, in this process, you'll learn some of the advanced concepts in JavaScript, how to use them, and why they can be used, and the same concepts in other programming languages cannot be implemented.

The application of all the source code can be github through this book. Table of contents about state reader object book structure JavaScript and Node.js JavaScript with you brief statement server-side JavaScript "Hello World" a complete Web application use case based on node.js using different modules to analyze and build applications The module of a basic HTTP Server Analysis HTTP server for function Pass function Pass is how to let the HTTP server work based on the event-driven callback server is how to handle the requested service side of the module put where to make the request of the "Routing" behavior driver execution route to the real request handler let please The processing program makes the implementation of a bad response blocking and non-blocking request response with non-blocking operation more useful scene processing post request processing File upload summary and Outlook JavaScript with Node.js JavaScript with you

Put aside the technology, let's talk about you and your relationship with JavaScript first. The main purpose of this chapter is to show you whether it is necessary for you to continue reading the following chapters.

If you're like me, then you start using HTML early to "develop", and that's why you're exposed to this interesting thing called JavaScript, and for JavaScript, you only have basic operations--adding interactivity to Web pages.

And what you really want is "dry goods," and you want to know how to build a complex web site--so you learn a programming language like PHP, Ruby, Java, and start writing "back end" code.

At the same time, you're always looking at JavaScript, and with the introduction of some technology like Jquery,prototype, you're getting to know a lot of the advanced skills in JavaScript, It also feels that JavaScript is not simply window.open ().

These are, after all, front-end technologies, although it always makes sense to use jquery when you want to enhance the page, but in the end, you're the most JavaScript user, not the JavaScript developer.

Then, there's the Node.js, the service-side JavaScript, how cool it is.

So you think it's time to pick up the familiar and unfamiliar JavaScript. But don't worry, writing node.js apps is one thing; understanding why they write in the way they write means-you have to understand JavaScript. It's a real game this time.

Here's the problem: since JavaScript is truly in two, or even three, forms (from the 90 's as a small toy for DHTML, to a strictly front-end technology like jquery, to the current service-side technology), it's hard to find a " The right way to learn JavaScript so that you can write node.js applications and feel like you're actually developing it instead of just using it.

Because that's the key: You're already an experienced developer, and you don't want to learn new technology by looking around for solutions (which may be incorrect) to make sure you learn the technology in the right way.

Of course, there are some excellent learning JavaScript articles out there. However, sometimes it is not enough to rely on those articles alone. What you need is guidance.

The goal of this book is to provide you with guidance. Brief statement

The industry has very good javascript programmers. And I'm not one of them.

I was the one I described in the previous section. I'm familiar with how to develop back-end web apps, but I'm just new to "real" JavaScript and node.js. I've only recently learned some of the advanced concepts of JavaScript and have no practical experience.

Therefore, this book is not a "beginner to proficient" book, more like a "Beginner to Advanced" book.

If successful, then this book is the first I began to learn node.js most want to have the tutorial. Service-side JavaScript

JavaScript is first run in the browser, but the browser simply provides a context that defines what can be done with JavaScript, but does not "say" too much about what the JavaScript language itself can do. In fact, JavaScript is a "complete" language: It can be used in different contexts, and its capabilities are more than those of other similar languages.

Node.js is actually another context that allows JavaScript code to run on the back end (out of the browser environment).

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.

To use Node.js, you first need to install. 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, go back and read the contents of the book below. "Hello World"

OK, "nonsense" not much said, immediately began our first Node.js application: "Hello World".

Open your favorite editor and create a helloworld.js file. All we have to do is output "Hello world" to stdout, which is the code that implements the feature:

Console.log ("Hello World");

Save the file and execute it through Node.js:

Node Helloworld.js

Normally, it will output Hello World at the terminal.

Well, I admit the application is a bit boring, so let's go for some dry goods. a complete Web application use case based on Node.js

Let's make it simple, but it's also practical: users can use our apps through browsers. 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.

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

Further, in the process of accomplishing this goal, we need more than just basic code, regardless of the elegance of the code. We also need to abstract this to look for a way to build more complex node.js applications. Application of different module analysis

Let's break down this application and what we need to implement in order to implement the use cases above. We need to provide a Web page, so we need an HTTP server for different requests, according to the requested URL, our server needs to give a different response, so we need a route to the request handler (request handler) When the request is received by the server and routed through routing, it needs to be processed, so we need the final request handler route to be able to process the post data and encapsulate the data in a more user-friendly format for delivery to the request handler, so the request data processing function is required Not only do we have to deal with URL-specific requests, we also have to display 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

Let's start by thinking about how we would build this structure using PHP. Generally we will use an Apache HTTP server and match 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 sounds like there's a lot of work to do, but then we realize that it's not a problem for node.js.

Now we're going to start the implementation path, starting with the first part of the--http server. Building the Application module a base HTTP server

When I was ready to start writing my first "real" node.js application, I didn't know how to write Node.js code or how to organize the code.
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 if I want to add more content, I want to keep the code readable.

In fact, it's fairly straightforward to keep code separate as long as you put code from different functions into different modules.

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.

So, now we're going to create a master file that launches our application, and a module that holds our HTTP server code.

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

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:

var http = require ("http");

Http.createserver (function (request, response) {
Response.writehead ({"Content-type": "Text/plain"});
Response.Write ("Hello World");
Response.End ();
}). Listen (8888);

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

Node Server.js

Next, open the browser to visit http://localhost:8888/, and you will see a Web page with "Hello World".

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

So next, let's 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.

Let's temporarily ignore the function definition in the Http.createserver bracket.

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

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.

The most interesting (and, if you used to use a more conservative language, such as PHP, which is odd) 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 as well as other variables. Perform function pass

For example, you can do this:

function say (word) {
console.log (word);
}

function Execute

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.