Nodejs First Impressions

Source: Internet
Author: User

Beginner Nodejs, specially in this record study process, is to this time a summary bar, mutual encouragement, common progress, now Begin:

1. What is Nodejs

The Nodejs is an event-driven, non-blocking I/O model designed to easily build responsive and easy-to-expand network applications. Packaged based on the Google V8 engine, the V8 engine performs JavaScript efficiently and quickly. Nodejs is actually a parser that is used to perform various operations. Modules or objects such as file Operations (FS), HTTP or HTTPS, and buffer are built into the Nodejs.

2. How to install Nodejs

Nodejs installation can be downloaded and installed directly in https://nodejs.org/.

3. Examples of Getting Started

First, create a simple HTTP service and return "Hello Nodejs":

 var  http = require ("http"  var  server = http.createserver (function   (req,res) { if  (req.url!=="/favicon.ico  "" {Res.writehead ( 200,{"Content-type": "Text/plain" });        Res.write ( "Hello Nodejs" );                Res.end (); Req.on ( "End", function   () {Console.log (         "Client request data is all received" );    }); }}). Listen ( 1337, "localhost" ); Console.log ( "HTTP server has been created and started listening"); 

Save the above code as a JS file such as: Http_server.js, and then in the cmd window to switch to the path of the file, using the command: node http_server.js, you can create a simple HTTP server. Then enter in the browser: http://www.127.0.0.1:1337, observe the browser window output: Hello Nodejs, and cmd window output: The HTTP server has been created and started listening (newline) the client requests the data to complete the reception. Such a simple HTTP service creation and request processing is complete. Here are some instructions:

    • Using the Require statement can be directly imported Nodejs built-in module, that is, the HTTP module here (generally speaking, a module is a package of various functions of the JS file, the use of direct require can be)
    • After importing the HTTP module, use the HTTP Createserver method to create an HTTP service that contains a function parameter, which is interpreted as a callback function, which is the one that executes after the HTTP service is created successfully. The callback function comes with req, res representing HTTP request, response respectively. If the decision is only to filter out the browser favorite icon of the request, can be ignored (PS: If not filtered, maybe your cmd window will print out 2 data, because not only the "/" root path is requested, but also in passing the "/favico.ico" path)
    • Using the Writehead method of the Res object, write the header file for the HTTP response, specifying a status code of 200 and a response type of text/plain. The Write method is used to directly respond to the text to the browser side, and end indicates the end of the response
    • On indicates that an end event is registered for the Req object, which is automatically invoked when the request ends, that is, event-driven. Automatic processing with built-in callback function after the end event responds normally
    • After the HTTP service is created, you also need to specify the specific URLs, ports, etc. that the service listens to, using listen to
    • Console.log indicates that the output is printed directly in the CMD window

4, exports

The exports object is an export object of the current module that is used to export public properties or methods within the module. So that other modules can use require direct import, module export object default to a normal object, if you want to change to a function, you can do the following:

function () {    console.log ("Hello World") ;

5. Path parsing rules for require

The Require function supports absolute paths that begin with a slash (/) or a drive letter (c:), and a relative path that starts with a./.

    • If passed to require is the default module under Node_modules, do not do path parsing, directly return the internal module export object, such as: Require ("FS");
    • Nodejs defines a node_modules directory for storing modules, such as the absolute path of a module is/home/user/hello.js, in which the module is requested using require ("Foo/bar"), which in turn requests the following path:/ Home/user/node_modules/foo/bar,/home/node_modules/foo/bar,/node_modules/foo/bar

6. NPM Package Use

NPM is a package management tool that is installed with Nodejs and uses NPM to install packages of various modules. NPM is relatively simple to use, such as to install packages named ARGV Package, directly in the cmd window input: npm install argv.

NPM package installed with local installation and global installation of two kinds, global installation using: NPM install-g argv, global installation and local installation is the difference between the local installation of the package if you want to reference in the CMD window, you should switch to the directory where the package is located, the global installed package does not have to switch directories.

7, about Webstorm&express

Express is a Web development framework based on Nodejs, which, in common with the SSH framework in Java, encapsulates many existing modules, such as request, Response, router, etc., and provides many powerful features to help create a variety of web and mobile device applications.

About Express Specific introduction http://www.expressjs.com.cn/,Webstorm to JS file support is very good, known as the Smartest JavaScript IDE, The following highlights the creation of a simple project under Webstorm:

  1. Download and install webstorm,\\192.168.20.50\tech\soft\ development tools \webstorm
  2. After opening the IDE select: File--New project,,template General Select Ejs (a view template engine), Set up a direct click on Create a Nodejs project based on Express (PS: General create may require the designation of Nodejs source code, then directly on the official website to download and specify)
  3. Just create a good project structure where the Bin\www file represents the project launch configuration, including port number settings. The Node_modules directory saves a series of modules that are automatically introduced by the current project (if you want to import another module, you can copy it directly from the NPM installation). The public directory holds referenced resource files, including images, CSS, and so on. Routes stores the routing module, which handles various URL requests. Views Directory save View resources. The App.js file is responsible for referencing various middleware modules as well as error handling. The Package.json file holds some configuration information.
  4. App.js file, where use indicates that all request methods are intercepted, using routes or users for specific URL request processing. Equivalent to routing relay functionality.
  5. The Index.js file code is as follows, processing the corresponding URL request separately:
    varExpress = require (' Express ');varRouter =Express. Router ();/*GET home page.*/Router.get (‘/‘,function(req, res, next) {if(Req.url!== "/favicon.ico") {Res.render ("Index", {title: "Express"});  Next (); }}); Router.use ("/list",function(req,res,next) {if(Req.url!== "/favicon.ico") {Console.log ("Router.use/add Request return Information"); //next ();}}); Module.exports= Router;

  6. In the browser, enter: http:localhost:3000, observe the output as follows: A simple Express application is now complete.

Complete one of the additions and deletions to verify the example:

Click to download Nodejs_crud

Nodejs First Impressions

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.