Use node. js for server-side JavaScript programming (1)

Source: Internet
Author: User
Tags node server

With the popularity of Web 2.0 concepts and Ajax technology, JavaScript has become a popular feature as an essential part of Ajax application development. Developers are gradually familiar with and familiar with JavaScript, and have accumulated relevant development experience. Although JavaScript is currently mainly used in Web applications and uses a browser as a running platform, some related attempts have been made to migrate JavaScript to the server, including Jaxer of Aptana. This approach is similar to Google GWT. Google GWT allows developers to write Web Front-end code in Java. These two methods aim to reuse the knowledge and accumulated experience that developers have mastered. In this regard, node. js is similar to Jaxer.

Simply put, node. js is a framework that allows developers to write server-side code in JavaScript. That is to say, the JavaScript code can be directly run on a local machine, not just a browser. From the implementation point of view, Jaxer and node. js both use the existing JavaScript execution engine. Jaxer uses the JavaScript engine used in Mozilla Firefox, while node. js uses the V8 engine used in Google Chrome.

Getting started with node. js

Node. js can run on mainstream operating systems such as Linux, Windows, and Macintosh. If you run node. js on Windows, Cygwin or MinGW is required. The following describes the common Windows platform as an example. Install Cygwin first. During installation, select gcc-g ++, make, openssl, python, and other packages. The gcc version must be the latest. Download the source code of node. js version 0.4.0 from the address provided in the references. After downloading and decompressing the package, run the./configure, make, and make install commands in Cygwin for compilation and installation. After the installation is complete, run the node command to start the command line provided by node. js. You can directly enter and run JavaScript code in the command line. You can also run a JavaScript file server. js through node server. js.

In code list 1, a simple "Hello World" program example is provided. After node helloworld. js is used to run the JavaScript file, "Hello World" is output on the console ".

Listing 1. Using node. js's "Hello World" program

 
 
  1. process.stdout.write("Hello World"); 

In code list 1, process indicates the currently running node. js process, and its attribute stdout indicates the standard output stream of the process. Use the write () method to write a string to the stream. From the code list 1, you can see that using JavaScript can access resources on the local system, such as the standard output stream. This reflects the strength of node. js from one aspect.

In node. in JavaScript code that can be run by js, you can use some global objects, including the process used in code list 1. The following describes the require () used to load modules () indicates the _ filename of the currently executing JavaScript file name, the _ dirname of the directory of the currently executing JavaScript file, and the setTimeout () similar to that in the browser for executing the scheduled task () and setInterval.

After introducing the basic knowledge of node. js, we will introduce the modular structure of node. js.

Modular structure

Node. js uses the module system defined by CommonJS. Different functional components are divided into different modules. Applications can choose to use appropriate modules based on their own needs. Each module exposes some common methods or attributes. The module user can directly use these methods or attributes without the implementation details inside the module. In addition to multiple modules preset by the system, the application development team can also use this mechanism to split the application into multiple modules to improve code reusability.

Modules

Using a module in node. js is very simple. Before using a module, you must first declare its dependencies. In JavaScript code, you can directly use the global function require () to load a module. For example, require ("http") can load the preset http module of the system. Require ("./myModule. js") is used to load the myModule. js module in the same directory as the current JavaScript file. If the require () path starts with "/", it is regarded as the absolute path of the module JavaScript file on the operating system. If this is not the case, node. js will try to find it in the parent directory of the current JavaScript file and the node_modules directory under its parent directory. For example, the directory/usr/home/my. in js, require ("other. js "), node. js will search for the following files in sequence:/usr/home/node_modules/other. js,/usr/node_modules/other. js and/node_modules/other. js.

The Return Value of the require () method is the public JavaScript Object exposed by this module, which contains available methods and attributes. Code List 2 shows the basic usage of the module.

List 2. Basic usage of modules

 
 
  1. var greetings = require("./greetings.js");   
  2. var msg = greetings.sayHello("Alex", "zh_CN");   
  3. process.stdout.write(msg); 

As shown in code list 2, the return value of the require () method is usually assigned to a variable, which can be directly used in JavaScript code. The greetings. js module exposes a sayHello () method, which is directly used by the current JavaScript code.

Develop your own modules

The basic task of developing a module is to write module-related code in the JavaScript file corresponding to the module. This encapsulates the internal processing logic of the module. Generally, a module exposes some public methods or attributes to its users. The internal code of the module needs to expose these methods or attributes. Code listing 3 shows the greetings. js file used in code listing 2.

Listing 3. greetings. js Module Content

 
 
  1. Var versions ages = {
  2. "Zh_CN": "Hello ,",
  3. "En": "Hello ,"
  4. };
  5. Exports. sayHello = function (name, language ){
  6. Return ages [language] | ages ["en"] + name;
  7. };

As shown in code list 3, the exports object content is included in the return value of the require () method called by the Module User. The module declares the exposed public methods and attributes in this way. Variables defined in the module, such as ages, are only visible to the Code in the module.

If a module contains a large amount of content, it can also be organized in folders. You can create a package. json file under the root directory of the folder, which contains the module name and the path of the JavaScript file. If the package. json file is not provided, node. js searches for the index. js file in the folder by default as the module's startup JavaScript file.

After introducing the modular structure of node. js, we will introduce its event-driven mechanism.

Event-driven

Those who have developed Web applications are familiar with the event processing mechanism in the browser. When you are interested in a certain event on a DOM element, you only need to register an event listener on the DOM element. For example, ele. addEventListener ("click", function () {}) adds a listener for the click event. When an event occurs, the JavaScript method of the event listener is called. The event processing method is asynchronous. This asynchronous execution method is very suitable for developing high-performance concurrent network applications. In fact, the current high-performance concurrent application development generally has two ways: the first is to use a multi-threaded mechanism, and the other is to use an event-driven approach. The problem of multithreading lies in the difficulty of application development and the possibility of thread hunger or deadlocks, which puts forward higher requirements for developers. The event-driven approach is more flexible and easy to understand and use by Web developers, and there are no issues such as thread deadlocks. Relying on the powerful Google V8 engine and Advanced event I/O architecture, node. js can become a good foundation for creating high-performance server-side applications.

The development of applications based on node. js has similar programming models with the development of Web applications. Many modules expose some events and use the code of these modules to add corresponding processing logic by registering the event listener. Code list 4 provides a simple HTTP Proxy server implementation code.

Listing 4. HTTP Proxy Server

 
 
  1. Var http = require ("http ");
  2. Var url = require ("url ");
  3.  
  4. Http. createServer (function (req, res ){
  5. Var urlObj = url. parse (req. url, true); // obtain the proxy URL
  6. Var urlToProxy = urlObj. query. url;
  7. If (! UrlToProxy ){
  8. Res. statusCode = 400;
  9. Res. end ("URL is required. ");
  10. }
  11. Else {
  12. Console. log ("processing proxy requests:" + urlToProxy );
  13. Var parsedUrl = url. parse (urlToProxy );
  14. Var opt = {
  15. Host: parsedUrl. hostname,
  16. Port: parsedUrl. port | 80,
  17. Path: (parsedUrl. pathname | "") + (parsedUrl. search | "")
  18. + (ParsedUrl. hash | "")
  19. };
  20. Http. get (opt, function (pres) {// request the content of the proxy URL
  21. Res. statusCode = pres. statusCode;
  22. Var headers = pres. headers;
  23. For (var key in headers ){
  24. Res. setHeader (key, headers [key]);
  25. }
  26. Pres. on ("data", function (chunk ){
  27. Res. write (chunk); // write back data
  28. });
  29. Pres. on ("end", function (){
  30. Res. end ();
  31. });
  32. });
  33. }
  34. }). Listen (8088, "127.0.0.1 ");
  35.  
  36. Console. log ("the proxy server has been started on port 8088. ");

The implementation of the entire proxy server is relatively simple. The createServer () method in the http module is used to create an HTTP server, and then the HTTP server can be listened on a specific port through the listen () method. The parameters passed in the createServer () method are the response methods of the HTTP request. In fact, each HTTP request corresponds to a request event on the HTTP server. The HTTP server creation part in code list 4 is actually equivalent to the implementation method given in code list 5.

Listing 5. How to create an HTTP server using the event mechanism

 
 
  1. var server = http.createServer();   
  2. server.on("request", function(req, res) {   
  3. }); 

In the request processing method, the content of the proxy URL is obtained through the http. get () method. Event-based processing is also adopted here. Pres. on ("data", function (chunk) {}) adds a processing method to the pres data event. The function of this method is to return the obtained content to the response of the original HTTP request when the content of the proxy URL is obtained. The same is true for end events. When using node. js for development, you will often encounter such scenarios that use event processing methods and callback methods.

After introducing the node. js event-driven mechanism, the following describes some common modules.


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.