Nodejs Start--(1)

Source: Internet
Author: User

Let's start with a brief introduction to Nodejs

We know that JavaScript is running in a browser, and the browser provides a context for it, allowing JavaScript to parse and execute.

Nodejs can actually understand that it is another context that allows the execution of JavaScript code in the backend (out-of-browser environment) parsing.

Because it uses Google's V8 virtual machine (the context the Google Chrome browser uses), the code can be executed with Veritas.

Nodejs can also be output directly from the console, in addition to displaying the results on the browser side.

Features of Nodejs

The main features of Nodejs are non-blocking, event-driven, single-process. The author of Nodejs said that his goal of creating Nodejs was to achieve a high-performance Web server, and he first valued the advantages of the event mechanism and the asynchronous IO model rather than JS, which is more suitable for lightweight, scalable, real-time data interaction applications. Nodejs built up a lot of objects, such as HTTP,FS, we can use it to build our HTTP server, on the server to develop.

Installation

For my part, I seldom go to work in Linux, so there is only one way to install Windows. How to install Linux on your own online search it. I'll post someone else's.

Install the dependency pack first 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 heard that to pay attention to the Python version of the problem, the recommended version of 2.6+, the lower version of the node installation error will occur,

Query Python version can be entered in terminal: PYHTON-V

Windows under

Installation is very simple, the last Officer network, the latest version of the MSI file download, directly installed ~ can modify the path.

All the way down no block

After the installation is successful, the latest version of the default has been put into the system path inside, do not have to control.

You can then go to the Start menu to find Nodejs open its command line entry, the default is to enter the C drive, generally or switch to the installation path of the disk, such as my e-drive

See if Nodejs is installed successfully, view its version number Node-v

Then simply test, first enter the node command, and then direct console input console.log ("Hello");

Because the Console.log method actually has a return value, there is no return for him, so the second one is undefined

  Let's test it again, this time we're going to see Hello world!

Create a new Main.js file under the installation path (e.g. I am E:\Program files\nodejs), enter

var http = require (' http '); Http.createserver (function  (req, res) {  Res.writehead, {' Content-type ': ' Text/plain '    });  Res.end (' Hello world\n ');  }). Listen ("127.0.0.1"); Console.log (' Server running at Http://127.0.0.1:3000/');

then input node main.js in the execution (general node inside exit is to press once or two times Ctrl + C), then the server has been set up ~
Enter the address in the browser: http://localhost:3000

Our Hello world has come out ~

Then explain this little piece of code first.

var http = require (' http '); As mentioned above, HTTP is a built-in object module in Nodejs, we introduce it in the form of require (object modules are generally introduced, we can build our own modules, and then introduce them, mentioned later).

Then HTTP now has one method for this object module, Http.createserver (), this method creates a service and then listens for an address: Http.createserver (). Listen (PORT,IP)

Thus building a server.

There is an anonymous function in Createserver (), which is mainly used to deal with related information. Req is request Request,res is reply response. Req is generally used for parsing processing in the request phase, such as the handling of URL characters in a common get address bar. Res is typically used to respond to requests, such as the write response header response Body rendering page, and so on.

Here, Res.writehead (content-type ': ' Text/plain ') is equivalent to writing a response header, Res.end (' Hello world\n '), which is equivalent to writing a response body.

Nodejs provides many built-in object methods, such as Http,fs,eventemitter,url and so on.

Refer to the official documentation for the use of these items

Or Taobao set up a platform Cnodejs, go inside and hang out.

And this 7-day learning Nodejs.

This is how the basic HTTP server is built, and the following is a description of node's powerful tool NPM (node Packages Manager, package management tool).

It is mainly used for managing our packages, downloading installation packages or uninstalling packages, and so on.

Older versions of node need to be downloaded from the installation, but the new version is already integrated. So just enter npm-v here to view its version ~

NPM is generally installed in two ways, global or local

Well, let's start with the experience and put on an express frame.

(Express.js is an MVC development framework for NODEJS and supports a variety of templates such as Jade,ejs)

We can install it in two ways:

Global installation: NPM install--g Express. (I found--g or-G can) this way will install the package into the global path inside, usually the C-drive npm/node_modules/below

Oh, wow ....

Don't care about the mistakes.

Next use I want to express-v (uppercase) to see its version of it

Some friends may encounter the mistake, here put a netizen's ~

Workaround as it says: The new version will split the command tool, so install it separately NPM install-g Express-generator

I said, don't mind the details above. 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 already incompatible, so use the following  var  app = Express (); //  var  port = 3000;  var  ip = "127.0.0.1" ;app.listen (PORT,IP);  //  IP this parameter is not writable, the default local  app.get ( '/', function   (Req,res) {res.send ( "Hello world\n"  "Start Express server\n"); 

As shown above, the new version may be error-less method

Express encapsulates HTTP, so you can directly use the method it defines.

Then the browser input http://localhost:3000/again

Then we will briefly introduce the above code. The rest doesn't have to be said. App.get () This is actually a routing process.

Okay, let's try the routing process.

varExpress = Require ("Express");//var app = Express.createserver (); The new version is already incompatible, so just use the one belowvarApp = Express ();//or direct var app= require ("Express") ();varPort = 3000;varip = "127.0.0.1"; App.listen (PORT,IP);//IP This parameter is not writable, the default localApp.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 to get is the path address, and the second parameter is the callback function.

You can do different things by using different address paths.

For example, different browser addresses can be routed:

11 of the USER/11 in the top is treated as the parameter ID value of the user. We can get the corresponding parameter value by Req.params this global method req.params.id

For Express, there is a more general approach, which is to use it directly to create a project:

For example, I would like to create a project Express_test enter

Express-e Express_test

OK, project creation is successful, look at the structure of it ~

After the project is created successfully, generate four folders, master file app.js and configuration information file Packetage.json

Bin is the startup file for the project , which configures how the project is started, the default NPM start

Public is the static file of the project , place JS css img and other files

routes is the routing information file for the project , which controls the address routing

views are view files , place template files Ejs or jade etc. (in fact, the equivalent of HTML file ~)

An MVC framework pattern like Express is a basic component of a Web project .

The finer parts are not to be considered first, let's start with the simple.

See no, the first step is wrong, because it does not know what the project, so first enter the project you want to start. CD Express_test

And then it went wrong, what's going on?

See, it can not find the required modules, so generally when we create a new project, we must first install the corresponding module .

we use NPM install directly , it will automatically detect Package.json file download and install the corresponding module

All right, then start it.

OK, start successfully, browser input address to see ~

The default port is 3000, you can go to the bin inside the www file to view, or modify it yourself ~

Wow, it worked! This is how the Simple Express project is.

The Express module is simply introduced here. More express will continue to say at the back ~

Finally, talk about the above mentioned require related knowledge

Writing a slightly larger program typically blocks the code. In Nodejs, the code is generally reasonably split into different JS files, each file is a module, and the file path is the module name.

In writing each module, there are require, exports, module three pre-defined variables available for use.

  The Require function is used to load and use other modules in the current module, passing in a module name and returning a module export object.

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

As an example:

var express = Require ("Express"); var func1 = require ("./func1"); // is the Func1.js module under the same path as the current Main.js var func2 = require (".. /nodejs/func2 "); // Func2.js is located under the same path as the main.js parent file

  The exports object is an exported object of the current module that is used to export the module's public methods and properties.

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

Like the func1.js mentioned above.

We can write code like this and then lead it out:

function () {     Console.log ("This is Func1");}; /* or so function func1 () {     Console.log ("This is Func1");} EXPORTS.FUNC1 = func1; */

The module object can access some information about the current module, but the most useful is to replace the exported object of the current module.

For example, the module export object is a normal object by default and can be used in the following way if you want to change to a function.

function () {      console.log (' Hello world! ' );  };


As a result, the module default export object is replaced with a function. We can directly in Main.js the var app = require ("./func1") (); Manipulated the

You can also export the form of an object:

//Inside the Func1.js ,Module.exports =function(name, age) { This. Name =name; This. Age =Age ; This. about =function() {Console.log ( This. Name + ' is ' + This. Age + ' years old '); }; }; //and then in Main.js ,varFUNC1 = require ('./func1.js ')); varR =NewFUNC1 (' Xiaoming ', 12); R.about (); //Xiaoming is years old

-----------well above is the start of Nodejs, there is no discovery, good magic. --------------

Nodejs Start--(1)

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.