This article provides a detailed introduction to nodejs environment installation, file structure, and routing. It is a very good article, and I recommend it to you here.
Run nodeJS
The first step is to install the nodeJS environment. Now it is faster to install nodeJS in windows. Download it directly:
Http://www.nodejs.org/download/
Download the node as needed. After the download is complete, go to the next step. After the download is complete, we have the nodeJS environment.
Step 2: to facilitate subsequent operations, we directly saw a folder blog on drive D.
Open the windows command line tool, go to disk D, and enter:
The Code is as follows:
Express-e blog
Then there may be dependency packages. We need to go to the blog directory for installation (the installation configuration is provided by package. json ):
The Code is as follows:
Npm install
In this way, we downloaded the dependent package. The dependent package and the java package file, and the. net bll file should be a concept.
At this time, our program can run:
The Code is as follows:
Node app
The Code is as follows:
D: \ blog> node appExpress server listening on port 3000
When the browser is opened, the following response is returned:
Here we use express (a popular nodeJSweb development framework) and the ejs template engine.
File structure
The directory structure of the initialization file is as follows:
App. js is the entry file
Package. json is a module dependent file. When we use npm install, it downloads related packages online with its configuration.
Node_modules is the downloaded module File (package. json)
Public stores static resource files
Routes stores route files
Views stores view template files
In this way, the basic directory structure is ready. Let's briefly describe the node_modules directory.
Node_modules/ejs
As we just said, the downloaded modules are stored here. To put it bluntly, it is a set of js files.
The Code is as follows:
Var parse = exports. parse = function (str, options ){
Var options = options | {}
, Open = options. open | exports. open | '<%'
, Close = options. close | exports. close | '%>'
, Filename = options. filename
, CompileDebug = options. compileDebug! = False
, Buf = "";
Buf + = 'var buf = []; ';
If (false! = Options. _ with) buf + = '\ nwith (locals | |{}) {(function (){';
Buf + = '\ n buf. push (\'';
Var lineno = 1;
Var consumeEOL = false;
For (var I = 0, len = str. length; I <len; ++ I ){
Var stri = str [I];
If (str. slice (I, open. length + I) = open ){
I + = open. length
Var prefix, postfix, line = (compileDebug? '_ Stack. lineno =': '') + lineno;
Switch (str [I]) {
Case '= ':
Prefix = "', escape (" + line + ',';
Postfix = ")),'";
++ I;
Break;
Case '-':
Prefix = "', (" + line + ',';
Postfix = "),'";
++ I;
Break;
Default:
Prefix = "');" + line + ';';
Postfix = "; buf. push ('";
}
Var end = str. indexOf (close, I)
, Js = str. substring (I, end)
, Start = I
, Include = null
, N = 0;
If ('-' = js [js. length-1]) {
Js = js. substring (0, js. length-2 );
ConsumeEOL = true;
}
If (0 = js. trim (). indexOf ('include ')){
Var name = js. trim (). slice (7). trim ();
If (! Filename) throw new Error ('filenameoption is required for include ');
Var path = resolveInclude (name, filename );
Include = read (path, 'utf8 ');
Include = exports. parse (include, {filename: path, _ with: false, open: open, close: close, compileDebug: compileDebug });
Buf + = "'+ (function () {" + include + "}) () + '";
Js = '';
}
While (~ (N = js. indexOf ("\ n", n) n ++, lineno ++;
If (js. substr (0, 1) = ':') js = filtered (js );
If (js ){
If (js. lastIndexOf ('//')> js. lastIndexOf ('\ n') js + =' \ n ';
Buf + = prefix;
Buf + = js;
Buf + = postfix;
}
I + = end-start + close. length-1;
} Else if (stri = "\\"){
Buf + = "\\\\";
} Else if (stri = "'"){
Buf + = "\\'";
} Else if (stri = "\ r "){
// Ignore
} Else if (stri = "\ n "){
If (consumeEOL ){
ConsumeEOL = false;
} Else {
Buf + = "\ n ";
Lineno ++;
}
} Else {
Buf + = stri;
}
}
If (false! = Options. _ with) buf + = "') ;}) (); \ n} \ nreturn buf. join ('');";
Else buf + = "'); \ nreturn buf. join ('');";
Return buf;
};
For example, here we use the ejs template and express module, and then we are curious to go into the ejs program to see what is the difference
Open it. After ejs. js, we can draw a bit of code to see that we are familiar with this Code. It is consistent with the template engine code idea of underscore and parses the Template into a string.
Then, convert it to a Function using the eval or new Function method, and pass in your own data object for better parsing.
As for the specific workflow, we do not know yet. We can only research it on the back. Now we are entering other modules.
App. js
As an entry file, app. js plays an important role:
The Code is as follows:
/**
* Module dependencies.
*/
Var express = require ('express ');
Var routes = require ('./routes ');
Var user = require ('./routes/user ');
Var http = require ('http ');
Var path = require ('path ');
Var app = express ();
// All environments
App. set ('Port', process. env. port | 3000 );
App. set ('view', path. join (_ dirname, 'view '));
App. set ('view engine ', 'ejs ');
App. use (express. favicon ());
App. use (express. logger ('dev '));
App. use (express. json ());
App. use (express. urlencoded ());
App. use (express. methodOverride ());
App. use (app. router );
App. use (express. static (path. join (_ dirname, 'public ')));
// Development only
If ('development' = app. get ('env ')){
App. use (express. errorHandler ());
}
App. get ('/', routes. index );
App. get ('/users', user. list );
Http. createServer (app). listen (app. get ('Port'), function (){
Console. log ('express server listening on port' + app. get ('Port '));
});
We use the require () command to load the express and http modules, and load template files such as index user in the routes directory.
App. set ('Port', process. env. port | 3000) to set the PORT at startup.
App. set ('view', _ dirname + '/view') is the path for storing the template file, where _ dirname is a global variable and stores the directory where the current script is located, we can view the following information:
The Code is as follows:
Console. log (_ dirname); // Add the following code to index. js:
/**
D: \ blog> node app
Express server li
D: \ blog \ routes
*/
We do not need to pay attention to how this _ dirname is obtained.
App. set ('view engine ', 'ejs') to set the template engine to ejs
App. use (express. favicon () is an image file under public if you want to modify the setting icon.
App. use (express. logger ('dev'); express depends on connect. Here the built-in middleware will output some logs.
App. use (express. json (); used to parse the Request body. Here, the string is dynamically converted to a json object
App. use (express. methodOverride (); connect built-in middleware, used to process post requests, and can disguise http methods such as put
App. use (app. router); Call router resolution rules
App. use (express. static (path. join (_ dirname, 'public'); connect built-in middleware, set public under the root directory to store static files
The Code is as follows:
If ('development' = app. get ('env ')){
App. use (express. errorHandler ());
}
This statement indicates that an error message is output during development.
The Code is as follows:
App. get ('/', routes. index );
App. get ('/users', user. list );
These two statements are specific file processing at the access time. For example, when you access the file directly, the default access is routes. index.
Then the template data is parsed internally:
The Code is as follows:
Exports. index = function (req, res ){
Console. log (_ dirname );
Res. render ('index', {title: 'express '});
};
Finally, the above Code will be called to create an http server and listen to port 3000. After successful, you can access the server on the webpage.
Routing
We used this method to build a route
The Code is as follows:
App. get ('/', routes. index );
The above code can be replaced by this Code (written in the app)
The Code is as follows:
App. get ('/', function (req, res ){
Res. render ('index', {title: 'express '});
});
This Code indicates that when you access the home page, the ejs template engine is called to render the index. ejs template file.
Now let's make a few changes. The above code implements the routing function, but we cannot put the routing-related code into the app. When there are more routes, the app will become bloated, so we put the configuration in the index.
Therefore, you can delete the routing functions in the app and add the code at the end of the app:
The Code is as follows:
Routes (app );
Then modify index. js
The Code is as follows:
Module. exports = function (app ){
App. get ('/', function (req, res ){
Res. render ('index', {title: 'express '});
});
};
How the code is organized is not clear yet, and we will take a look at it later.
Routing rules
Express encapsulates a variety of http requests. We generally use get/post
The Code is as follows:
App. get ();
App. post ();
The first parameter is the request path, the second parameter is the callback function, or the two parameters are request and response.
Then, there are the following rules for req (request ):
Req. query processes get requests and obtains get Request Parameters
Req. params processing/: get or post requests in the form of xxx
Req. body processes the post request and obtains the post Request body.
Req. params processes get and post requests, but the search priority is req. params-> req. body-> req. query
The path rules also support regular expressions. Let's talk about the rules later ......
Add routing rules
When we access a nonexistent link:
Because there is no routing rule for/y, he does not mention the files under public, so it is 404.
Now we add related routes in index. js:
The Code is as follows:
Module. exports = function (app ){
App. get ('/', function (req, res ){
Res. render ('index', {title: 'express '});
});
App. get ('/Y', function (req, res ){
Res. send ('Ye xiaohaid ');
});
};
Here my page is garbled:
The reason is that after the download, my file is gbk encoded. We need to change it to UTF-8. We will ignore the template engine. We will go to the next section.
Registration Function
Here we will provide a simple registration function with the original blogger. Here we use mongo db as the database, and then we will improve the functions in sequence.
Create a new register route and create a register template for it.
① Create a route in index
The Code is as follows:
App. get ('/register', function (req, res ){
Res. render ('index', {title: 'registration page '});
});
The Code is as follows:
Module. exports = function (app ){
App. get ('/', function (req, res ){
Res. render ('index', {title: 'express '});
});
App. get ('/Y', function (req, res ){
Res. send ('Ye xiaohaid ');
});
App. get ('/register', function (req, res ){
Res. render ('register ', {title: 'register page '});
});
The Code is as follows:
<% = Title %>
<% = Title %>
In this way, our page is formed:
The basic program is ready. Now we need database support, so we need to install the mongoDB environment.
MongoDB
MongoDB is a type of NoSQL Based on Distributed File storage. It is written in C ++ and the data structure supported by MongoDB is loose. It is similar to json. We know that json can support any type, so we can create a complicated structure.
The Code is as follows:
{
Id: 1,
Name: 'Ye xiaochai ',
Frinds :[
{Id: 2, name: 'suram '},
{Id: 3, name: 'One-page Book '}
]
}
Install MongoDB
First go to the terminal
Open the command line tool to switch the directory to bin, and enter:
The Code is as follows:
Mongod-dbpath d: \ mongodb \ blog
Set the blog folder as the project directory and start the database. For the convenience of writing a command later, click it to start the database:
The Code is as follows:
D: \ mongodb \ bin \ mongod.exe-dbpath d: \ mongodb \ blog
Link to MongoDB
After the database is successfully installed, our program still needs the relevant "driver" program to connect to the database. At this time, we need to download the package ......
Open package. json and add a new line to dependencies
The Code is as follows:
{
"Name": "application-name ",
"Version": "0.0.1 ",
"Private": true,
"Scripts ":{
"Start": "node app. js? 1.1.9"
},
"Dependencies ":{
"Express": "3.4.8 ",
"Ejs ":"*",
"Mongodb ":"*"
}
}
Then run npm install to download the new dependency package. In this way, the mongoDB-related driver is available. To connect to mysql and other databases, other dependency packages are required.
Create the setting. js file in the root directory to save the database connection information.
The Code is as follows:
Module. exports = {
CookieSecret: 'myblog ',
Db: 'blog ',
Host: 'localhost'
};
Db is the database name, host is the database address, and cookieSecret is used for cookie encryption and is irrelevant to the database.
Next, create the models folder under the root directory, and create db. js under the models folder.
The Code is as follows:
Var settings = require ('../settings '),
Db = require ('mongodb '). Db,
Connection = require ('mongodb '). Connection,
Server = require ('mongodb '). Server;
Module. exports = new Db (settings. db, new Server (settings. host, Connection. DEFAULT_PORT), {safe: true });
The Code is as follows:
New Db (settings. db, new Server (settings. host, Connection. DEFAULT_PORT), {safe: true });
Set the database name, database address, and database port to create a database instance, and export the instance through module. exports, so that you can read and write the database through require.
To successfully write data to the database, the server program needs to process the post information. Therefore, we create user. js in the models folder.
The Code is as follows:
Var mongodb = require ('./db ');
Function User (user ){
This. name = user. name;
This. password = user. password;
};
Module. exports = User;
// Store user information
User. prototype. save = function (callback ){
// User document to be stored in the database
Var user = {
Name: this. name,
Password: this. password
};
// Open the database
Mongodb. open (function (err, db ){
If (err ){
Return callback (err); // error. err information is returned.
}
// Read the users set
Db. collection ('users', function (err, collection ){
If (err ){
Mongodb. close ();
Return callback (err); // error. err information is returned.
}
// Insert user data into the users set
Collection. insert (user ,{
Safe: true
}, Function (err, user ){
Mongodb. close ();
If (err ){
Return callback (err); // error. err information is returned.
}
Callback (null, user [0]); // success! Err is null and the Stored User document is returned.
});
});
});
};
The Code is as follows:
// Read user information
User. get = function (name, callback ){
// Open the database
Mongodb. open (function (err, db ){
If (err ){
Return callback (err); // error. err information is returned.
}
// Read the users set
Db. collection ('users', function (err, collection ){
If (err ){
Mongodb. close ();
Return callback (err); // error. err information is returned.
}
// Search for a document whose User name (name key) value is name
Collection. findOne ({
Name: name
}, Function (err, user ){
Mongodb. close ();
If (err ){
Return callback (err); // failed! Returns err information.
}
Callback (null, user); // success! Returns the queried user information.
});
});
});
};
Here is a write data, a read data, and a processing program. Now you need to add the following program before index. js.
The Code is as follows:
Var User = require ('../models/user. js ');
Modify the app. post ('/register ')
The Code is as follows:
App. post ('/register', function (req, res ){
Var name = req. body. name;
Var pwd = req. body. password;
Var newUser = new User ({
Name: name,
Password: pwd
});
NewUser. save (function (err, user ){
// Related operations, write to session
Res. send (user );
});
});
Then click "register" to respond.
If you are not sure whether to write data to the database at this time, you can enter the database for query. First, switch to the database directory.
The Code is as follows:
D: \ mongodb \ bin>
Input:
The Code is as follows:
Mongo
Switch the database to the blog
The Code is as follows:
Use blog
Last Input
The Code is as follows:
Db. users. find ()
We are all happy to see Data Writing, so today's learning has come to an end.
Conclusion
Today, we have followed a blog post to complete the operations from installation to database writing. Tomorrow, let's add other aspects to gradually deepen nodeJS learning.