Nodejs server-side platform practice record

Source: Internet
Author: User
Tags emit

"Node. JS Learning Notes" by Lijun

01-note

Nodejs is a server-side JavaScript, a single-threaded, asynchronous I/O, event-driven JavaScript ; Its basic frame is as follows:

n Node Standard library (JavaScript Implementation)

N/C + + implementations

U Node Downlevel Interface

U V8 Core

U LIBUV/LIBIO/LIBEV/IOCP

Nodejs is An implementation of the CommonJS specification API.

2-note

Nodejs Download, install, test (Windows version ), run,npm node Package Management installation Supervisor

v:https://nodejs.org

V-Mount Nodejs 4.1.2

V Test:win+r command-line window test instruction:node , Result:>, two times Ctrl + C Can exit

V Create Notepad write:console.log ("This is a test for Nodejs"); Save As Test.js

v Command line window run test.js file directive: node path +test.js, enter to run

V npm installation Supervisor directive:NPM install-g Supervisor

3-note

Nodejs http,fs,events module Examples

n Http server:node_httpserver.js

var http=require ("http");

var server=new http. Server ();

Server.on ("Request", function (req,res) {

Res.writeheader (200,{"Content-type": "Text/html"});

Res.write ("

Res.end ("<p>this is a test for Nodejs httpsever</p>");

});

Server.listen (3000);

Console.log ("Nodejs httpserver is listening Port 3000");

N Run httpserver.js:node httpserver.js Browser address input http://127.0.0.1:3000

N Fs File system:node_fs.js

var fs=require ("FS");

function Callbackf (err,data) {

if (ERR)

Console.error (ERR);

Else

Console.log ("The data of Test.txt: \ n" +data);

}

Fs.readfile ("Node_fs.js.txt", "UTF-8", CALLBACKF);

N Events :node_event.js

var event=require ("Events");

Var emiter=new event. Eventemitter ();

function Callbackf (param1,param2) {

Console.log ("Name:" +param1+ "Password:" +param2);

}

Emiter.on ("MyEvent", CALLBACKF);

Emiter.emit ("MyEvent", "Lijun", "123456");

Emiter.emit ("MyEvent", "admin", "123456");

n Creating and Loading modules

① Create:

Mymodule.js

function Hello () {

var name;

This.setname=function (pname) {

Name=pname;

}

This.sayhello=function () {

Console.log ("Hello" +name);

}

}

Module.exports=hello;

② Loading :

Node_testm.js

var hello=require ("./node_module.js.txt");

var myhello=new hello ();

Myhello.setname ("Nodejs");

Myhello.sayhello ();

Run Test:node Node_testm.js

N 12

4-note

Express Framework for developing WEB Applications

N Installation Express:npm install-g Express and npm install-g express-generator

n Create Express project:express-t ejs project name ( current directory Creation )

n follow the prompts into the project folder : CD project name, reinstall dependency : npm Install

n Setting environment variables set debug= project name:*, then start npm:npm start

N Browser Test created Web project http://127.0.0.1:3000(old version Nodejs Run Project: Node App.js)

n Express Project Structure

  • App.js Project Startup and configuration Files
  • Package.json Project and dependency information
  • Views (index.ejs/jade) View folder ( files that inherit template engine layout )
  • Views (layout.ejs/jade) View folder ( template engine layout file )
  • Routes (index.js) Routing control folder ( Routing control File ) 
  • Public Common Services folder (javascripts subfolders /images subfolders /stylesheets Sub-folders )
  • Other

4-note

MongoDB Non-relational database and third-party Mongoose

N Download install new version of Windows MongoDB, unzip the package to complete the installation

N Create database folder named Database name dbname such as:E:\mongodb\dbname

N Enter E:\mongodb\bin\, set and start the db command:mongod-dbpath E:\mongodb\dbname

Express WEB Project to connect to the mongodb database and create a reply:

n Modify the project's package.json file:

"Denpendencies": "MongoDB": "*",

N Run npm Install dependency

n Create Db_setting.js in the project root directory

module.exports={

Cookiesecret: "Lijun",

DB: "MyDB",

Host: "LocalHost"

}

n Create the models folder in the project root directory , where db.jsis created:

var set=require (".. /db_setting "),

Db=require ("MongoDB"). Db

Connection=require ("MongoDB"). Server,

Server=require ("MongoDB"). Server;

Module.exports=new Db (set.db,new Server (Se.host,connection.default_port), {safe:true});

N Create a session

"Denpendencies": "Connect-mongo": "*",

N Run npm Install dependency

n Modify the app.js file:

var mongostore=require ("Connect-mongo") (express);

var set=require ("./db_setting");

after the methodoveride

App.use (Express.cookieparser ());

App.use (Express.session () {

Secret:set.cookieSecret,

Key:set.db,

COOKIE:{MAXAGE:1000*60*60},//1 Hour

Store:new Mongostore ({

Db:set.db

})

});

N

5-note

The basic instructions commonly used by MongoDB:

6-note

The Nodejs View Helper, which provides access to a global function or object through the View assistant. The View Assistant is divided into

① Static View helper: type can be any type of function ( subject to Parameters ) and Object

② Dynamic View Assistant: can only be a function under a type ( not subject to parameters ), access to response and request Object

Example:

App.helpers (

Inspect:function (obj) {

return obj;

}

);

App.dynamichelpers (

User:function (req,res) {

Rerurn Req.session.user;

}

);

7-note

Module Type: Core Module (http/fs/net/etc), file module (. json/.js/c++/c)

Module loading mechanism :

① with relative path "./ Module name (Require ("./setting.js "))" or ". / Module name (Require (". /setting.js ")" Mode load module

The first way require ("./setting.js"): The current file needs to be loaded with its own directory under the setting.js file; the second way require (".. /setting.js "): The current file needs to be loaded with its own directory x, and the x directory is located under the directory of setting. file.

② is loaded as an absolute path: first from the directory where the current file is located, then to the top-level directory lookup.

Load cache: When the same module is loaded again, it is loaded directly from memory instead of loading the same module into the cache again, which means that the memory is not repeatedly loaded with the same module instance that has been loaded.

Nodejs server-side platform practice record

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.