Let nodeJS run
The first step is of course to install the nodeJS environment. Now that Windows has a faster installation of nodeJS, you can download it directly:
http://www.nodejs.org/download/
Download it as needed. After the download is completed, just go to the next step. After that, we will have the nodeJS environment.
The second step is, in order to facilitate our subsequent operations, we directly saw a folder blog on disk D.
Then open the Windows command line tool, enter D disk, and enter:
Copy the code as follows:express -e blog
Then there may be dependency packages inside, we need to enter the blog directory to install (the installation configuration is provided by package.json):
Copy the code as follows: npm install
In this way, we download the dependency package, which depends on the package and Java package files and the .net bll file should be a concept
At this time, our program is ready to run:
Copy the code as follows:node app
Copy the code as follows: D:/blog>node appExpress server listening on port 3000
At this time, you will have a response when you open the browser:
Here we are using express (a popular nodeJSweb development framework) and use the ejs template engine
File structure
The initialization file directory structure is as follows:
app.js is the entry file
package.json is a module dependency file. When we use npm install, it will download related packages online according to its configuration.
node_modules is the downloaded module file (package.json)
public stores static resource files
routes Save routing files
views Store related view template files
In this way, our basic directory structure comes out. Let's briefly talk about the node_modules directory here.
node_modules/ejs
We just said that the downloaded module is stored here. To put it bluntly, it is a collection of js files
The code copy 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 consumptionEOL = 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('filename option 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;
};
Just like the ejs template and express module we used here, we then walked into the ejs program curiously to see what the difference is.
After opening, ejs.js, we draw some code to read: we are more familiar with this code. It is consistent with the template engine code of the underscore, and both parse the template into a string.
Then convert it into a function through the eval or new function method, and pass it into your own data object for parsing.
As for the specific workflow, we don’t know yet, so we can only put it in the later point to study. Okay, let’s go to other modules now.
app.js
As an entry file, app.js plays an important role:
The code copy 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('views', path.join(__dirname, 'views'));
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 load the express and http modules through the require() command, and will load the index user and other template files in the routes directory
app.set('port', process.env.PORT || 3000) is the port at startup
app.set('views', __dirname + '/views') is the path to store the template file. Where __dirname is a global variable, storing the directory where the current script is located. We can view it in this way:
The code copy is as follows:
console.log(__dirname);//index.js add the following code
/**
D:/blog>node app
Express server li
D:/blog/routes
*/
As for how this __dirname was obtained, we don't need to pay attention to it for the time being
app.set('view engine', 'ejs') sets the template engine to ejs
app.use(express.favicon()) is to set the icon to modify it, and then you can create the images file below public.
app.use(express.logger('dev')); express depends on connect, and the built-in middleware will output some logs.
app.use(express.json()); is used to parse the request body, where the string will be dynamically converted to a json object
app.use(express.methodOverride()); connect built-in middleware to handle post requests and can disguise put and other http methods
app.use(app.router); Call router resolution rules
app.use(express.static(path.join(__dirname, 'public'))); connect built-in middleware, set public in the root directory to store static files
The code copy is as follows:
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
This sentence means that error information should be output under development conditions
The code copy is as follows:
app.get('/', routes.index);
app.get('/users', user.list);
These two sentences are specific processing files at the access time. For example, when accessing directly here, the default access is routes.index.
Then it actually parses the template data inside:
The code copy 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 success, you can access it on the web page.
routing
We used this method to build the route
The code copy is as follows: app.get('/', routes.index);
The above code can be replaced by this code (written in the app)
The code copy is as follows:
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
This code means that when accessing the home page, the ejs template engine is called to render the index.ejs template file
Now make some modifications. The above code implements the routing function, but we cannot put the routing-related code into the app. If there are too many routes, the app will become bloated, so we put the relevant configuration into the index
So delete the relevant routing functions in the app and add code to the end of the app:
The code copy is as follows: routes(app);
Then modify index.js
The code copy is as follows:
module.exports = function(app) {
app.get('/', function (req, res) {
res.render('index', { title: 'Express' });
});
};
How this code is organized is not clear yet, so I won't pay attention to it anymore. Let's take a look at it later
Routing rules
Express encapsulates multiple http requests, we generally use get/post two
The code copy 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, for req(request) there are the following rules
req.query handles get request and gets the get request parameters
req.params handles /:xxx form get or post request
req.body handles post request and gets the post request body
req.params handles get and post requests, but the search priority is req.params->req.body->req.query
Path rules also support regularity, we will talk about the details later...
Add routing rules
When we access a link that does not exist:
Because there is no routing rule for /y, he doesn't say the file under public, so it's 404
Now we add the relevant route in index.js:
The code copy 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 Xiaochai');
});
};
Here I have garbled page:
The reason is that after downloading, my file is GBK encoding. We just need to change it to utf-8. We don’t care about the template engine. Let’s go to the next section.
Registration function
Here we follow the original blogger to do a simple registration function, use mongo db as the database, and then we will improve the functions in turn
Create a new register route and create a new register template for it, so let's start
① Create a new route in index
The code copy is as follows:
app.get('/register', function (req, res) {
res.render('index', { title: 'Register Page' });
});
The code copy 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 Xiaochai');
});
app.get('/register', function (req, res) {
res.render('register', { title: 'register page' });
});
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<form method="post">
<div>Username: <input type="text" name="name"/></div>
<div>Password: <input type="password" name="password"/></div>
<div><input type="submit" value="Login"/></div>
</form>
</body>
</html>
In this way, our page is formed:
With the basic program, we now need database support, so we need to install the mongoDB environment
MongoDB
MongoDB is a NoSQL based on distributed file storage. It is written in C++. The data structure supported by MongoDB is loose, similar to json. We know that json can support any type, so we can create a very complex structure.
The code copy is as follows:
{
id: 1,
name: 'Ye Xiaochai',
frinds: [
{ id: 2, name: 'Su Huanzhen' },
{ id: 3, name: 'One-Page Book' }
]
}
Install MongoDB
First, go to http://www.mongodb.org/downloads to download the installation file, then copy the file to D disk and rename it mongodb, and then create a new blog folder inside
Then open the command line tool to switch the directory to bin and enter:
Copy the code as follows: mongod -dbpath d:/mongodb/blog
Set the blog folder to the project directory and start the database. For the sake of convenience, we will write a command and click directly to start the database:
Copy the code as follows:d:/mongodb/bin/mongod.exe -dbpath d:/mongodb/blog
Link to MongoDB
After the database is installed successfully, our program also needs the relevant "driver" program to link the database. Of course, the package needs to be downloaded...
Open package.json to add a new line in dependencies
The code copy is as follows:
{
"name": "application-name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.8",
"ejs": "*",
"mongodb": "*"
}
}
Then run npm install to download the new dependency package. This way, drivers related to mongoDB are available. To link mysql and other databases, other dependency packages are needed.
At this time, create the setting.js file in the root directory to save the database connection information
The code copy is as follows:
module.exports = {
cookieSecret: 'myblog',
db: 'blog',
host: 'localhost'
};
db is the database name, host is the database address, cookieSecret is used for cookie encryption and has nothing to do with the database
Next, create a new model folder in the root directory and create a new db.js in the models folder
The code copy 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 copy 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 the database can be read and written by require
We need to successfully write to the database, and the server-side program needs to process the post information, so we create a new user.js in the models folder
The code copy is as follows:
var mongodb = require('./db');
function User(user) {
this.name = user.name;
this.password = user.password;
};
module.exports = User;
//Storing 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, return err information
}
//Read the users collection
db.collection('users', function (err, collection) {
if (err) {
mongodb.close();
return callback(err); //Error, return err information
}
//Insert user data into users collection
collection.insert(user, {
safe: true
}, function (err, user) {
mongodb.close();
if (err) {
return callback(err); //Error, return err information
}
callback(null, user[0]); //Success! err is null and returns the stored user document
});
});
});
};
The code copy 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, return err information
}
//Read the users collection
db.collection('users', function (err, collection) {
if (err) {
mongodb.close();
return callback(err);//Error, return err information
}
//Find a document with a username (name key) value name
collection.findOne({
name: name
}, function (err, user) {
mongodb.close();
if (err) {
return callback(err);//Failed! Return to err information
}
callback(null, user);//Success! Return the query user information
});
});
});
};
Here one writes data and the other reads data. There is a processor. Now you need to add the following program in front of index.js.
The code copy is as follows: var User = require('../models/user.js');
Modify the app.post('/register')
The code copy 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 session
res.send(user);
});
});
Then click to register and you will have a reaction
If you cannot determine whether to write to the database at this time, you can enter the database for querying and first switch to the database directory
Copy the code as follows:D:/mongodb/bin>
enter:
Copy the code as follows:mongo
Then switch its database to connect to the blog
Copy the code as follows: use blog
Last input
Copy the code as follows: db.users.find()
We all happily saw the data being written, so today's learning has come to an end for the time being
Conclusion
Today we followed a blog to complete the operation from installation to writing to the database. Let us add other aspects tomorrow and gradually deepen the learning of nodeJS.