Nodejs Study Notes

Source: Internet
Author: User

Nodejs Learning Document Collation 1, Nodejs is what:

Nodejs is a platform that JavaScript can run in the background, specifically to enable code JavaScript to run in the background, because it does not run in the browser, so it does not involve objects such as document. (Mozilla points out that JavaScript is made up of core JavaScript and Client JavaScript.) )

2. Nodejs How to run javascript:

Nodejs uses Google's V8 engine to execute JavaScript code (V8 is the fastest in the engine of JavaScript).

3, Nodejs characteristics:

node. JS replaces multi-threading with asynchronous I/O and event-driven, resulting in considerable performance gains. The Nodejs uses a single-threaded, non-blocking mode that allows CPU utilization to reach 100%. (single-threaded means that we write code code can only execute one line at a time, Nodejs itself is not single-threaded, for example, we call the Nodejs Ioapi, the system will open up the other thread through C/s, the Nodejs is the bottom of the C + + Nodejs itself provides HTTP services, which means you can easily implement a combination of a Web site and a server, and NODEJS projects do not require web containers like tomcat.

4, Nodejs suitable to do what, not suitable for what:

Suitable for: Web sites with complex logic, large-scale Web applications based on social networks, Web sockets, TCP/UDP sockets applications, command line tools, interactive terminal programs, local applications with graphical user interfaces, unit test tools, client-side JavaScript compilers 。

Not suitable for: 1. Computationally intensive program, 2. Single user multi-tasking application 3. Logic is a very complex transaction 4. Unicode and Internationalization

5. Installation and development environment: (value example under window)

Download NODEJS development Environment http://nodejs.org/download/always NEXT,NODEJS will automatically add the path to path, after installation you can enter path in CMD to view environment variables. You can enter node--version in cmd to view the version of Nodejs. Input node into node's command line mode, enter Console.log (' Test '), and you can see the output that you want to respond to in the console. Ctrl+d or two times Ctrl + C exits command line mode.

Write the first. js file, which can be executed in CMD using the node file name. such as Console.log ("Hello word!");

6. Create a Web project to handle different requests:

1. Building a routing module

Module function: Provide the requested URL and other required get and post parameters, then execute the corresponding code according to the data. Therefore, we need to look at the HTTP request and extract the requested URL and the Get/post parameter from it.

2. Building a program module for processing requests

Module function: Store different handlers and correspond to the requested URL

3. Combine the previous two modules with an HTTP server

First, build a routing module

Create a new Router.js write

Routing module that responds differently to different requests
Handle Processing Request method
function route (handle, pathname) {
Console.log ("About-route a request for" + pathname);
Checks whether the request handler for the given path exists, and calls the corresponding function directly if it exists
if (typeof handle[pathname] = = "function") {
Handle[pathname] ();
} else {
Console.log ("No request handler found for" + pathname);
}
}
Exports.route = route;
Ii. Building a program module for processing requests

Create a new Requesthandlers.js write

Store different handlers, corresponding to the requested URL
function Start () {
Console.log ("Request handler ' start ' was called.");
}
function upload () {
Console.log ("Request handler ' upload ' was called.");
}
Exports.start = start;
Exports.upload = upload;
Three, the previous two modules and the HTTP server together

The purpose of the routing module is to provide the requested URL and other required get and post parameters, and then execute the corresponding code based on that data. Therefore, we need to look at the HTTP request and extract the requested URL and the Get/post parameter from it.

All the data we need will be included in the request object, which is passed as the first parameter of the ONrequest () callback function. But in order to parse this data, we need additional node. JS modules, which are URLs and QueryString modules, respectively.

In the server.js, they were introduced

URL module: Resolving URLs

QueryString module: Parse the parameters of the Get and post request bands (again later)

Modify Server.js

Request (require) a Nodejs-brought HTTP module
Request (require) a Nodejs URL parsing module
var http = require ("http"),
url = require ("url");
Console.log (URL);
Returns an object that has a listen method with a numeric parameter,
Specifies the port number that this HTTP server listens on.
function start (route, handle) {
function onrequest (request, Response) {
Get Request Path
var pathname = Url.parse (request.url). Pathname;
Turn off Nodejs default Access Favicon.ico
if (!pathname.indexof ('/favicon.ico ')) {
};
Receive a request from pathname
Console.log ("Request for" + Pathname + "received.");
Router processing
Route (handle, pathname);
Return data
Response.writehead ($, {"Content-type": "Text/plain"});
Response.Write ("Hello world!");
Response.End ();
}
Http.createserver (ONrequest). Listen (8888);
Console.log ("Server has start!");
}
Open Interface
Exports.start = start;

Modify Index.js

var server = require ("./server"),
Router = require ("./router"),
Requesthandlers = require ("./requesthandlers");
Handle to save different request path corresponding processing method
var handle = {};
handle["/"] = Requesthandlers.start;
handle["/start"] = Requesthandlers.start;
handle["/upload"] = requesthandlers.upload;
Incoming routing module method, path processing method
Server.start (Router.route, handle);
Iv. Testing

Enter node index.js in the command panel

Http://127.0.0.1:8888/start

7, connect the database to MySQL for example:

Use Nodejs's own NPM Module (node package management module) to load the database connection module in the project path to execute NPM install MySQL can see the path under the Node_modules folder, there is a MySQL folder. Write file execution.

var mysql = require (' mysql ');

URL = ' localhost ';

USERNAME = ' root ';

PASSWORD = ' root ';

DATABASE = ' Testnode ';

var Mysqlcon;

Mysqlcon = Mysql.createconnection (

{

Host:url,

User:username,

Password:password,

Database:database

}

);

Exports.getdate = function GetDate () {

Mysqlcon.query (' select * from user where id=? ', [20],

function (err,re) {

if (err) {

Console.log (ERR);

}else{

Console.log (re);

}

}

);

}

8. Rapid Web project development using Express framework:

1. The express framework must be installed: Express installation commands are also updated and need to be installed Express-generator

$ NPM INSTALL-G Express//Global installation

$ NPM install-g express-generator//This command is not forgotten, otherwise it will prompt "express command cannot find"

Create a project with the directive EXPRESS-E project name

2. Establishment of website engineering structure:

Express-e Ejs Microblog

3. Follow the prompts to enter the folder installation

CD microblog//microblog the folder for the project you created earlier

NPM Install

Each time you modify the code, it restarts automatically. Lazy programmers are counting on this effortless tool to live:

Installation: NPM install-g Supervisor

Execution: Supervisor App.js

Nodejs Study Notes

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.