First glance at Node. js and node. js

Source: Internet
Author: User
Tags exit in

First glance at Node. js and node. js

First, let's briefly introduce nodeJS

We know that JavaScript is running in the browser, and the browser provides a context for it, so that JavaScript can be parsed and executed.

NodeJS can be understood in this way. It is another context that allows parsing and executing JavaScript code on the backend (out of the browser environment.

Because it uses Google's V8 Virtual Machine (the Context Environment used by Google's Chrome browser), the code can be executed with rational.

In addition to displaying results on the browser side, nodeJS can also be output directly on the console.

NodeJS features

NodeJS has the following features: non-blocking, event-driven, and single process. The author of NodeJS said that he created NodeJS to achieve high-performance Web servers. He first valued the superiority of the event mechanism and asynchronous IO model, rather than JS, which is more suitable for lightweight and scalable applications, suitable for Real-time Data Interaction applications. NodeJS has many built-in objects, such as http and fs. We can use it to build our HTTP server for development on the server.

Install

For myself, I seldom work in linux, so currently only install on Windows. For how to install Linux, search for it on the Internet.

Install the dependency package sudo apt-get install g ++ curl libssl-dev apache2-utils sudo apt-get install git-corethengit clone git: // github.com/joyent/node.git cd node./configure make sudo make install

I have heard that you need to pay attention to the Python version. We recommend that you install Python 2.6 or later. If you use a lower version, a Node installation error occurs,

To query the Python version, enter pyhton-v in the terminal.

Windows

The installation is very simple. on the official website, download the latest version of the msi file and install it directly ~ You can modify the path.

There is no obstacle

After the installation is successful, the latest version is installed in the system path by default.

Then you can go to the Start menu and find nodeJS to open its command line. By default, it is the drive C, which is usually switched to the disk where the installation path is located. For example, if my drive is an edisk

Check whether nodeJS has been installed successfully. Check the node-v version.

Run the node command and then enter console. log ("hello") on the console ");

Because the console. log method actually has a returned value, it is not returned here, so the second is undefined.

  Let's test it again. This time we will see Hello World!

Create a main. js file in the installation path (for example, E: \ Program Files \ nodejs) and enter

var http = require('http');  http.createServer(function (req, res) {   res.writeHead(200, {'Content-Type': 'text/plain'});    res.end('Hello World\n');  }).listen(3000, "127.0.0.1");  console.log('Server running at http://127.0.0.1:3000/');

  Enter node main. jsExecute (generally, the exit in the node is to press Ctrl + C once or twice), then the server has been set up ~
Enter the address http: // localhost: 3000 in the browser.

Hello World is coming out ~

Then let's explain the code.

Var http = require ('HTTP '); As mentioned above, http is the built-in Object Module in nodeJS. We use require to introduce it. (This is generally the case for object modules, we can also create our own modules, introduce them, and then mention them ).

Then there is a method in the http Object Module: http. createServer (). This method creates a service and then listens to another address: http. createServer (). listen (port, ip)

Thus, a server is built.

CreateServer () has an anonymous function, mainly used to process related information. Req is the request, and res is the response. Req is generally used for parsing at the request stage, for example, processing the url characters in the address bar of a common get request. Res is generally used for the corresponding operations after receiving the request, such as writing the response header to render the page.

Here, res. writeHead (200, {'content-type': 'text/plain '}); It is equivalent to writing a response header, res. end ('Hello World \ n'); It is equivalent to writing a response body.

NodeJS provides many built-in object methods, such as http, fs, EventEmitter, and url.

For more information about how to use these things, see the official documentation.

Or the platform CNodejs created by taobao. Go and check it out.

Learn nodeJS in the next seven days.

This is the basic HTTP server setup. Next we will introduce the powerful node tool npm (node packages manager and package management tool ).

It is mainly used to manage our packages, download the installation package or uninstall the packages.

The old version of node needs to be downloaded and installed by itself, but the new version has been integrated. So enter npm-v here to view its version ~

There are two npm installation methods: global or local

Well, let's try it out first and install an express framework.

(Express. js is an MVC development framework of nodejs and supports multiple templates such as jade and ejs)

You can install the SDK in either of the following ways:

Global installation: npm install -- g express. (I found that -- g or-g is acceptable) This method will install the package into the global path, which is generally under npm/node_modules/of drive C.

Wow ....

Don't care about the errors ..

Next I want to use express-V (in uppercase) to view its version.

Some friends may encounter errors. Here, I will post a netizen's ~

The solution is as follows: the new version separates the command tool, so you need to install npm install-g express-generator first.

As I said, do not care about the above details... O_O

Okay. Now let's try express?

Or the main. js. We changed it to this:

Var express = require ("express"); // var app = express. createServer (); // The new version is not compatible, so use the following var app = express (); // or directly var app = require ("express ") (); var port = 3000; var ip = "127.0.0.1"; app. listen (port, ip); // you can leave this parameter Unspecified. The default value is local app. get ('/', function (req, res) {res. send ("Hello World \ n") ;}); console. log ("start express server \ n ");

As shown above, the new version may report an error.

Express encapsulates http, so you can directly use the method defined by it.

Then input http: // localhost: 3000/in the browser.

Then let's briefly introduce the above Code. You don't need to talk about the rest. Let's just say app. get () is actually a route processing.

Okay. Let's try Route processing ~

Var express = require ("express"); // var app = express. createServer (); // The new version is not compatible, so use the following var app = express (); // or directly var app = require ("express ") (); var port = 3000; var ip = "127.0.0.1"; app. listen (port, ip); // you can leave this parameter Unspecified. The default value is local app. get ('/', function (req, res) {res. send ("Hello World \ n") ;}); app. get ('/one', function (req, res) {// or "/one/res. send ("one \ n") ;}); app. get ('/user', function (req, res) {// or "/user/" res. send ("user \ n") ;}); app. get ('/user/: id', function (req, res) {// or "/user/" res. send ("user:" + req. params. id) ;}); console. log ("start express server \ n ");

As shown above, the first parameter of get is the path address, and the second parameter is the callback function.

You can use different address paths to perform different operations.

For example:

The 11 in the user/11 in the top is treated as the user's parameter id value. We can use the global method req. params to obtain the corresponding parameter value req. params. id

There is actually a more common method for express, that is, using it directly to create a project:

For example, if you want to create the project express_test, enter

Express-e express_test

Okay. The project is successfully created. Check its structure ~

After the project is successfully created, Four folders are generated, the main file app. js and the configuration information file packetage. json.

Bin is the project Startup file. The default npm start method is used to configure how to start the project.

Public is the static file of the project, where files such as js css img are placed.

Routes is the project's route information file, controlling address Routing

Views are view files. They are placed in template files, such as ejs or jade. (In fact, they are equivalent to html files ~)

The MVC framework such as express is the basic component of a Web project.

Let's simply start it first ~

If you see no, the first step is wrong. Because it does not know what the project is, you must first enter the project you want to start. Cd express_test

What happened when an error occurs?

As you can see, it cannot find the required module. Therefore, when creating a new project, we should first install the corresponding module.

We can simply use npm install. It will automatically detect the downloading and installing the corresponding modules in the package. json file.

Okay, start it ~

OK. The startup is successful. Enter the address in the browser to view the information ~

The default port is 3000. You can check the www file in the bin or modify it by yourself ~

Wow ~ Successful! The simple express project is like this ..

The express module briefly introduces this. More about express later ~

Finally, let's talk about the above-mentioned require-related knowledge.

Code is generally modularized when you write a slightly larger program. In NodeJS, code is generally reasonably split into different JS files. Each file is a module, and the file path is the module name.

Each module has three predefined variables: require, exports, and module.

The require function is used to load and use other modules in the current module, input a module name, and return a module export object.

The module name can use a relative path (starting with./) or an absolute path (starting with a drive letter such as/or C:). The. js extension in the module name can be omitted.

For example:

Var express = require ("express"); var func1 = require (". /func1 "); // corresponds to the current main. var func2 = require (".. /nodejs/func2 "); // func2.js is located with main. js parent file in the same path

The exports object is the export object of the current module. It is used to export the public methods and attributes of the module.

When other modules use the current module through the require function, the exports object of the current module is obtained.

For example, func1.js mentioned above

We can write the code and export it as follows:

Exports. func1 = function () {console. log ("This is func1") ;};/* or function func1 () {console. log ("This is func1");} exports. func1 = func1 ;*/

The module object can access some information about the current module, but the most common purpose is to replace the export object of the current module.

For example, the export object of the module is a common object by default. If you want to change it to a function, you can use the following method.

module.exports = function () {    console.log('Hello World!'); };


In this way, the exported object of the module is replaced with a function by default. In main. js, we can directly use var app = require ("./func1 ") ();

You can also export the form of an object:

// Module in func1.js. exports = function (name, age) {this. name = name; this. age = age; this. about = function () {console. log (this. name + 'is' + this. age + 'ears old') ;};// then in main. in js, var Func1 = require ('. /func1.js'); var r = new Func1 ('xiaoming', 12); r. about (); // xiaoming is 12 years old

----------- Well, the above is the start of nodeJS. Is there any discovery? It's amazing ..--------------

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.