Nodejs Study Notes (i)

Source: Internet
Author: User
Tags php framework netbeans

recently the company to start a mobile project, in the back-end system selection, there are PHP, Java, NodeJS, technically speaking, Java is more mature, but the development speed is slow, performance is stable; PHP developed rapidly, but the stability is not high, performance is general, development efficiency is high The Nodejs has high performance and can handle more connection and IO problems, so the Nodejs is finally selected. Nodejs Nature is a server-side JavaScript, but it is not so easy to use, my general learning process is as follows, I bought two books, one is Pauling "in simple words nodejs", a Zhao Kun and so on "node. JS combat", relatively speaking, The former impact on me more, let me have an intuitive understanding of the Nodejs, the introduction of Pauling to the bottom, the framework of the very few less, I bought a second book, but just roughly doubled, frankly, I before the understanding of Nodejs equals zero, to jquery also only superficial research, So I met a lot of difficulties. Finally I cleaned up the idea and chose the Sails MVC framework. the problem I want to solve is also very simple, need to provide back-office support for mobile app, need to provide HTTP service, support MySQL database, and other cache database, and to the PHP framework Laravel developed web program interoperability, The first problem is the need to be able to encrypt and pair passwords using the same encryption algorithm. These issues will be resolved as follows. Nodejs installation is relatively simple, in the nodejs.org to download the corresponding operating System package, the current version is 0.10.31,windows and Mac platform can be installed directly, the Linux platform needs to compile itself, the compilation process is very simple, run in turn. Configure,make,sudo make install, now the Nodejs install NPM by default, is Nodejs package management tool, most of the modules can be installed through this tool. Common Nodejs resources are nodejs.org and github.com, which contain official documents, which can search for some of the packages you need, although most of the packages can be found on the web, but the tutorials are easy to get out of date, and it's best to look at the corresponding instructions on github.com, or after downloading the installation module , look at the readme.md in the module directory, you can know some basic usage, avoid spending too much time on the initial configuration. when looking for a module, you can look at its evaluation, looking for a better evaluation of the module, because the Nodejs module is too much. Development Nodejs, I know the tools have Nodeclipse, Netbeans, Webstorm, relatively speaking, webstorm better, but need money, nodeclipse is good, but feel unstable, NetBeans adds a plugin to it, but without debugging, it's just a running command, but it's very powerful in its editing function. Other sublime and notepad++ can be used, eventually I use NetBeans, because it can be a common environment with PHP, Java program, Eclipse is a bit too big, recently not like it. Nodejs program other programs such as PHP, Java is very different, if it is wrong in some place, the whole system crashes, but PHP and Java are not, they will only error in the place, and other places normal operation. Because Nodejs essentially, its main thread is only one, and the crash is gone. So be very careful, but also have its advantages, access to global variables is much easier, such as sessioin, cache and so on. However, there is also a need to pay attention to its memory allocation problem, global variables may always exist, prone to memory leak problems. Install the Nodejs module in the command of NPM install Module_name, which will create a node_modules in the current directory, which is included in the module, if you want to install the global module, you need to use NPM install Module_name-g , this creates the node_modules in the home directory, which stores the included modules. The module name can be specified in the command, or it can be specified in the Package.json in the current directory. Let's take a look at Express for an example. Learning Nodejs Common component is express, which is a simple MVC framework that provides HTTP service, similar to PHP laravel, or Java Spring, of course, its function is weaker, the installation command for NPM install-g Express, and then install it with the Express command, in the following situations:Express #在当前目录下创建express框架, using the Jade engine by defaultExpress-e #在当前目录下创建express框架, the Ejs engine is used by default
Express project# Create the Express framework under project directory, using the Jade engine by default express-e project# Create the Express framework in the project directory, using the Ejs engine by defaultExpress--version #显示当前版本You can also use Express-h to view all the Help informationThe current version of Express is 4.9.0, after 4.0, the default Express framework is no longer integrated with the Common connect module, the detailed connect information can refer to https://github.com/senchalabs/ Connect, for example, to add session support, refer to the Express-session module on the page. There are two default page rendering engines: Jade and Ejs,ejs are similar to PHP in the way the JS script embedded in the HTML code, although it seems messy, but accustomed to nothing, jade a bit difficult to understand, not adapt, as if efficiency is not high, chose the Ejs engine. The default Package.json is as follows{"name": "Test","version": "0.0.0","Private": true,"Scripts": {"Start": "Node./bin/www"  },"dependencies": {" Express": "~4.9.0"," body-parser": "~1.8.1"," cookie-parser": "~1.3.3"," Morgan": "~1.3.0"," Serve-favicon": "~2.1.3"," Debug": "~2.0.0"," Ejs": "~0.8.5 "  }}after running the EXPRESS-E command, you will be prompted to run the NPM install command in the directory, which will be installed according to the properties of the Package.json dpendencies download module. If you need to add session support, you can run NPM install express-session, or you can add a line to Package.json dependencies, as follows"dependencies": {" Express": "~4.9.0"," body-parser": "~1.8.1"," cookie-parser": "~1.3.3"," Morgan": "~1.3.0"," Serve-favicon": "~2.1.3"," Debug": "~2.0.0"," Ejs": "~0.8.5"," express-session": "*"  }You can then run the NPM Install command. The command to run Express is as follows:  node./bin/www is in the root directory under the bin directory of the WWW file, which is a JS file, after running, you can view the results of the operation in the browser, the default home for the http://localhost : The directory of the 3000,express framework is also very clear, roughly as follows D:.│ app.js                               #主要的入口文件, or start file │ package.json                 &N Bsp #模块配置文件 │├─bin│     www                           #启动文件: Command for node www│├─public                         &N Bsp   #一些静态文件, slices, JS, CSS files │ ├─images│ ├─javascripts│ └─stylesheets│          Style.css│├─routes                     #路由文件, currently Express supports placing requests in a virtual directory To the routing file, which is defined in App.js │     index.js                 #app. Use ('/', RO Utes)  -> the root directory of Routes  │     users.js                 #app. Use ('/user ' , users)  ->user in directory │└─views                       #mvc的vie W layer, currently Ejs file         error.ejs        Index.ejs However, for now, Express does not support controllers, whose logic is often written in the routes file, but logic can be placed in other files and then require in. The default route file Index.js is as follows: var express = require (' Express '); var router = Express. Router ();  /* GET home page. */router.get ('/', function (req, res) {  res.render (' index ', {title: ' Express '});  module.exports = router;This is also very easy to understand, there is only one route for the root directory, is accessed by the Get method, the corresponding function has two parameters, req and res, divided into input objects and output objects. Specific API descriptions can be accessed from the main site page:http://expressjs.com/4x/api.html, here's a brief summary.1) Reqreq.params.name->/user/:namereq.query.name->/user?name=shiyqreq.body.name. Form input value named namethree inputs, Req.param (name), are supported in the order of Params,body,queryReq.cookie.name->cookie's Name property2) ResRes.cookie (name,value), setting cookiesres.redirect ('/foo/bar '), jump to/foo/barres.location (' Foo/bar ') like redirectres.send (' <p>name</p> ') to browser outputRes.json (), want the browser to return JSON data    res.render (view, [locals], callback), turn to view, and carry variableres.end (), End outputlet express support session, need to install Express-session module, view the corresponding module under the Readme.md file, you can see the following contentvar express = require (' Express ')var session = require (' express-session ')var app = Express ()App.use (Session ({secret: ' Keyboard Cat ',Resave:false,saveuninitialized:true }))This express-session need to follow the definition of Express, its use is app.use (), if the position is too close, there may be problems, need attention, Its default usage is Req.session.name, the default express-session will save the session in memory, if you want to save to Redis,memcache and MongoDB, need to integrate additional components, You can find it on github.com and remember to read the Readme.md file .So far , the basic Express development can be done, but it is easy to find that the code is changed, the system does not take effect, Nodejs does not have the so-called hot-start mechanism, need to restart the program, but each boot is too troublesome, so to use the auto-start tool, Supervisor, the installation mode is NPM install SUPERVISOR-G, the command is Supervisor App.js, you can use Supervisor-h to view the help, generally need to set the-W or-I switch,-W represents the monitoring directory, Only the files in these directories are modified to restart node, default to the current directory ".", the Directory with "," interval,-I is to ignore some directories. The-w switch is useful, for example, when some programs create temporary files in the current directory, they are restarted and need to be set up only if certain directory modifications are required, such as the sails Framework, which has the following directory structureNodejs Study Notes (i)There is obviously a temporary file. tmp, if you run Supervisor App.js directly, there will be a continuous restart, so I wrote a sailsjs.bat file in the root directory, the contents ofsupervisor-w api,assets,config,node_modules,tasks app.jsThis will solve the problem of constant restart.     

Nodejs Study Notes (i)

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.