Nodejs Novice Village Guide--30 minutes to get started

Source: Internet
Author: User
Tags install mongodb

Profile

# Ready to Work

# Start a simple service

# Routing

# Three ways to get parameters

# static files

# Database Integration

#async Solving multiple nesting problems

This article is suitable for no NODEJS project development experience and want to have a general understanding of Nodejs you read, 30 minutes to get started, maybe not

*****************************************************

# Ready to Work

After installing Nodejs, create a new folder named Demo-project, create a new file in the folder root directory app.js as the portal file for the Nodejs app.

Open terminal (called Command prompt on window), enter demo-project root directory, enter the following command and return to initialize Package.json

NPM Init

The command line prompts you to enter the project name name/version version/describes the description, use the default value (press ENTER directly) is good, after entering the description prompted to enter the application entry file name entry point, If your entry file name is not called App.js, enter the corresponding name, otherwise return all the way to the completion of initialization.

After the initialization is complete, the Demo-project root directory will be more than one Package.json file, the content is like this

{  "name": "Node-project",  "version": "1.0.0",  "description": "",  "main": "App.js",  "Scripts": {    "test": "Echo \" Error:no Test specified\ "&& Exit 1 "  },  " author ":" ",  " license ":" ISC "}

Next install express,express is a Web development framework based on the Nodejs platform

NPM Install Express--save

Preparations are over.

# Start a simple service

Express opening a service is very simple, in three steps: introduction of the express=> instantiation and the listening port

var express = require (' Express '),    = Express (),    =app.get;  function(req, res) {    res.send (' Hello world 'function() {    Console.log (' server has started ~ ');})

In terminal input node App.js start service

Open browser access: localhost:3000, page successfully print out Hello World

Change the App.js "Hello World" to "Hello, JavaScript", press CTRL + C to stop the service and then enter node App.js (or press the arrow keys directly). Enter to restart the service, refresh the browser, successfully print out "Hello, JavaScript", In order to avoid the tedious thing of restarting a service once, you need to install Supervisor to listen for file changes and restart the service automatically.

NPM Install Supervisor--save

MAC Player installation failure try installing sudo as an administrator in front of the command

sudo npm install supervisor--save

Start the service after the installation is complete use the Supervisor App.js command, which is to start and listen to the file status, found that the file changes to automatically restart the service immediately, no longer need to use node app.js.

# Routing

Route = Path + HTTP method

Routing is made up of a path and a specific HTTP method, each of which can correspond to multiple processing functions, the basic infrastructure app. Method (Path, HANDLER), the app is an instance of Express, method is one of the HTTP request mode, path is the server path, HANDLER is the function that the route executes when it matches

Several routing instances, which can be modified by using AJAX to change the request type to verify the following three interfaces

function (req, res) {    res.send (' This is a GET request ');}) App.post (function(req, res) {    res.send (' This is a POST request ');}) App. Delete function (req, res) {    res.send (' This is a delete request ');})

The HANDLER function has two parameters req/res, namely Request/response, the request header and the response header, which can be used to get the requested parameters, the path of the current page, and so on, and the response header can return data to the page or render the specified page.

There are three ways to get parameters, see:# Three ways to get a parameter

The Res.render method specifies the page that the browser renders, such as writing a route to the home page, a path of/, and passing data to the first page {title: ' Home '}

Create a new folder under the project root views storage view, under the new Index.jade,jade is the Nodejs template engine, syntax is very concise, similar to the Ejs template

// Specify the view path and template engine Jade var path = require (' path '); App.set (' views ', Path.join (__dirname, ' views ')); App.set (' view Engine ', ' Jade '); // Routing function (req, res) {    res.render (' index ', {        ' home '    })})

Index.jade

HTML    Head        title #{title}    body        . Content here is #{title}

Rendering

# Three ways to get parameters

Express gets three ways to get the parameters passed over the front end

1, pass through the path, obtain with Req.params.key

// Routing function (req, res) {    console.log (req.params.name)    res.render (' index ', {        ' home '    })})  //  If the path is Http://localhost:3000/wangmeijian//  Console.log ( Req.params.name)//  result Wangmeijian

2, get the way to pass, with Req.query.key get

// Routing function (req, res) {    console.log (req.query.sex)    res.render (' index ', {        ' home '    })})  //  If the path is http://localhost:3000?sex=20//  Console.log (req.query.sex)  //  results

3, the request parameter as long as contains the key value pair, uses req.body obtains, borrows the Express official website example, App.use is the middleware, what is the middleware? Is that any request must pass through it, it can modify req and res, can terminate the request, can call the next middleware

varApp = require (' Express ')();//rely on Body-parser and multer to parse parametersvarBodyparser = require (' Body-parser '));varMulter = require (' Multer ')); //MiddlewareApp.use (Bodyparser.json ());//For parsing Application/jsonApp.use (bodyparser.urlencoded ({extended:true}));//For parsing application/x-www-form-urlencodedApp.use (Multer ());//For parsing Multipart/form-dataApp.post (‘/‘,function(req, res) {Console.log (req.body); Res.json (req.body);})

# static files

File directory

Jade template to refer to the static directory under the single CSS, JS, IMG and other resources, You need to host static resources through Express.static, Express.static is the only built-in middleware for Express (4.xx version), and other middleware requires additional installation

App.use (express.static (' static '));

Access is available after hosting, note that the access path does not contain static

Http://localhost:3000/img/a.jpg
Http://localhost:3000/css/b.css
Http://localhost:3000/js/c.js

# Database Integration

Service side of course to have a database, NODEJS support a variety of databases, the more popular include Mysql/mongodb,mongodb can be directly in the form of JSON storage data, MongoDB without the concept of tables and columns, and corresponding to the collection and the field

Install MongoDB yourself first, then install the Mongoose package, mongoose it is easy to operate MongoDB in Nodejs

NPM Install Mongoose--save

Mongoose has three concepts, patterns/models/Documents

Patterns are used to define data types

The model is compiled by schema and can be understood as a constructor

The document is an instance of the pattern, and if you don't understand, look at the chestnuts.

varMongoose = require (' Mongoose '));//localhost is a mongodb address, local installation uses localhost, TestDB is the database name, if not present it will be automatically createdMongoose.connect (' Mongodb://localhost/testdb ',function(err) {if(err) {returnConsole.error (ERR); } console.log (' Database connection succeeded ');})//patterns, defining data typesvarStudentschema =NewMongoose. Schema ({name:string, age:number})//model, the first parameter is the model name, the second parameter is the schema name, the third parameter is the collection name, and if not, MongoDB automatically adds s as the collection name after the model namevarStudent = Mongoose.model (' Student '), Studentschema);//DocumentvarStudent =NewStudent ({name:' Zhang San ', Age:21st})//save method stored in databaseStudent.save (function(err) {if(err) {returnConsole.log (Err)} console.log (' Data insertion succeeded ')    //model. Find Method QueryStudent.find ({age:21},function(err, result) {if(err) {returnConsole.error (ERR); } console.log (' Query result: ') Console.log (Result)})})

#async Solving multiple nesting problems

The above student.save only once stored data and then query, code only a layer of nesting, if there is a business scenario, there are 5 student information data inserted into the database, insert the completion of the query immediately after the 5 data, according to the above will have 6 layers nested, nested more, maintenance is a problem, how to solve this problem?

The Async.each method solves this problem and, of course, it needs to be installed separately, and Async provides simple and powerful functions to handle JavaScript asynchronous programming.

NPM Install async--save

Syntax: Async.each (coll, iteratee, Callback), official documents

Collection of Coll Traversal

Iteratee iterative Process

Callback callback, which triggers callbacks when an iteration is completed or an error occurs during an iteration

Chestnuts??

/*#async解决多重嵌套*/varAsync = require (' async ');varStudentschema =NewMongoose. Schema ({name:string, age:number})varStudent = Mongoose.model (' Student '), Studentschema);vardata = [    NewStudent ({name:A, Age:18    }),    NewStudent ({name:' B ', Age:28    }),    NewStudent ({name:C, Age:32    }),    NewStudent ({name:' d ', Age:26    }),    NewStudent ({name:E, Age:29})]async.each (data,function(item, callback) {Item.Save (function(Err) {callback (ERR); })},function(err) {if(Err) {Console.log (err); }    //no error indicates that the data is fully inserted and can be queriedStudent.find ({},function(err, result) {if(err) {returnConsole.log (ERR);    } console.log (Result); })})

Query results

{__v:0, age:28, name: ' B '0, age:18, Name: ' A '0, age:26, name: ' d '0, age:32, name: ' C '  0, age:29, Name: ' E ', _id:572d965bcd38199a9c3817c6}

With Async.each asynchronous Process Control, goodbye nesting, code looks comfortable.

In the end, the chestnuts are demo-project.

These are some of the problems that Nodejs initially need to understand or encounter in the novice village. If it is helpful, you can give some encouragement ~

Wang Meijian
Source: Http://www.cnblogs.com/wangmeijian
This article copyright belongs to the author and blog Garden All, welcome reprint, reprint please indicate source.
If you feel that this blog post for your gain, please click on the bottom right corner of the [recommended], Thank you!

Nodejs Novice Village Guide--30 minutes to get started

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.