Blog program ideas built with node. JS (node. js Real-School reading note 1)

Source: Internet
Author: User

has been learning node for some time, before the Great node. js, the basic understanding of some of the basic usage of node and some concepts, and then began to see the second node. JS Combat, the first chapter is to build a blog program. But have to spit slot node, developed too much, many libraries have been and before the use of the same, will always go to Baidu Google to inquire about the latest usage, in fact, I think this is not necessarily a good thing, because it is not stable, so it is not good to learn, it is necessary to maintain the attention of node. No nonsense, this article will probably say some of the things learned in this chapter, experience summary
1, express-Web application Development framework based on node. JS Platform
This blog is based on the framework of this development, an MVC architecture, The author of the framework, however, has turned to go in 04. Because the previous PHP development contact with Yii and thinkphp, are MVC, so this is better to get started, but also better understand, this framework is node above the most people use.
Installation is simple, using NPM

-g express-generator

This is the program to install Express (not the project, only add this program to create an express project)
Then you can create a new project (project)

-ecd blog && npm install

Like this, a blog project is set up, and then just run.
You can run NPM start directly at the root of the project or into the bin directory directly node www is all right, probably look at the directory structure

App.js: Boot file, or portal file
Package.json: Storage of Engineering information and module dependencies, when adding dependent modules in dependencies, running NPM install,npm checks Package.json in the current directory and automatically installs all specified modules
Node_modules: Store the modules installed in the Package.json when you add the dependent modules to the Package.json and install them in this folder
Public: Store image, CSS, JS and other files
Routes: Storing Routing files
Views: Store view files or template files.
Bin: Storing executable files
Let's take a look at app.js. This is the portal file, which is the main file that the program runs

//Start with the introduction of a variety of modulesvarExpress =require(' Express ');varPath =require(' path ');varFavicon =require(' Serve-favicon ');varLogger =require(' Morgan ');varCookieparser =require(' Cookie-parser ');varBodyparser =require(' Body-parser ');//Introduction of two routesvarRoutes =require('./routes/index ');varUsers =require('./routes/users ');//This should be called instantiation of the project.varApp = Express ();//Set the view directory and use the template engine, here using Ejs, about Ejs, this is the HTML inside how to output the variables inside the object, and in HTML nested PHP code very much likeApp.set (' views ', Path.join (__dirname,' views ')); App.set (' view engine ',' Ejs ');//ICO of the project//app.use (Favicon (__dirname + '/public/favicon.ico '));//Log-Logged middlewareApp.use (Logger (' Dev '));//parsing son's middlewareApp.use (Bodyparser.json ());//Parsing URL encoded request MiddlewareApp.use (bodyparser.urlencoded ({extended:false}));//Middleware for parsing cookiesApp.use (Cookieparser ());//Here is express now the only built-in middleware, static file storage directoryApp.use (Express.static (Path.join (__dirname,' Public ')));//This uses routing, in fact, we can write all the methods in the App.js, but this is not good maintenance, we should take the method alone, put in index.js inside, here just use hisApp.use ('/', routes); App.use ('/users ', users);//404 pages in simple termsApp.use ( function(req, res, next) {    varErr =New Error(' not Found '); Err.status =404; Next (err);});//Error handlers//Development Error Handler//would print StackTraceif(App.get (' env ') ===' development ') {App.use ( function(err, req, res, next) {Res.status (Err.status | | -); Res.render (' ERROR ', {message:err.message, error:err}); });}//Production error Handler//No stacktraces leaked to userApp.use ( function(err, req, res, next) {Res.status (Err.status | | -); Res.render (' ERROR '{message:err.message, error: {}}); Module.exports = app;

Then you can write all kinds of methods in Index.js.

2. Commissioning
In general, after we modify the code, we have to stop the previously running project and then re-open, this is different from PHP, this will be very troublesome, but we can solve the problem through a module

$ npm install -g supervisor

Install supervisor. Start app.js with the Supervisor command:

$ supervisor app.js

This does not have to turn off every time and then open, but in fact, so when the code is wrong, it will always restart execution, difficult to see the wrong hint, in fact, not good.

3. Middleware
What is middleware, in fact, this I also want to find a lot of information, behind the discovery of simple as PHP plug-ins, introduced can realize some functions, do not need you to make a lot of trouble to achieve
4, the page notification flash
In PHP, we can use some alter and the like to remind users of some information, in node or express, you can use the Flash function, is also a middleware, the following code can be used to do hints, such as the

So in the following return of which jump page has this log out of the success of the prompt
5, Crypto
This is a node above a cryptographic algorithm, because JS comes with no MD5 and the like encryption algorithm, so it is necessary to use these, built-in some MD5, SHA1, SHA256, sha512 and other algorithms, the use of methods.

First included in

crypto  require(‘crypto‘);var md5  = crypto.createHash(‘md5‘);        password = md5.update(‘需要加密的字符串‘).digest(‘hex‘);

The last password is encrypted after the string, the last side of the digest (' Hex ') is the role of 16 binary format to do the output, because the default is 2 binary, there will be garbled, in fact, there are many other encryption methods. Refer to this article for details
Https://cnodejs.org/topic/504061d7fef591855112bab5

6. Multer Upload Module

varExpress =require(' Express ')varMulter =require(' Multer ')//Here is the definition of the upload folder, this is the absolute path, it is recommended to add dirname these before, or back to the root of your server to uploadvarUpload = Multer ({dest:' uploads/'})varApp = Express ()//First, this means you upload only one file, and the file name is AvatarApp.post ('/profile ', Upload.single (' Avatar '), function (req, res, next) {  //Req.file is the ' avatar ' file  //Req.body'll hold the text fields, if there were any})//Up to 12 folders with the same name photos, if more, will be an errorApp.post ('/photos/upload ', Upload.array (' photos ', A), function (req, res, next) {  //Req.files is array of ' photos ' files  //Req.body'll contain the text fields, if there were any})//This is a one-time definition of more than the name of the filevarCpupload = Upload.fields ([{name:' Avatar ', MaxCount:1}, {name:' gallery ', MaxCount:8}]) App.post ('/cool-profile ', Cpupload, function (req, res, next) {  //Req.files is an object (String-, array) where FieldName is the key, and the value is array of files  //  //e.g.  //req.files[' Avatar '][0], File  //req.files[' gallery '), Array  //  //Req.body'll contain the text fields, if there were any})

But in fact, these are not very good, because they are uploaded at the time also need to re-write the name of the file, because the upload to the server file name is randomly generated, there is no suffix, so I wrote a model to unify the implementation

varMulter =require(' Multer ');varStorage = Multer.diskstorage ({//Set the file path after uploading, the uploads folder will be created automatically. Destination function (req, file, cb) {cbNULL,'. /public/images ')     },//Rename the uploaded file, get the Add suffix nameFileName function (req, file, cb) {        varFileFormat = (file.originalname). Split ("."); cbNULL, File.fieldname +'-'+Date. Now () +"."+ Fileformat[fileformat.length-1]); } });varMulterutil = Multer ({storage:storage}); Module.exports = Multerutil;

Here is the definition of the Upload folder and upload the file after the naming method, using the following methods

varMuilter =require('. /models/multerutil.js ');//define several upload files at the front end here.varupload = Muilter.fields ([{name:' File1 '}, {name:' File2 '}, {name:' File3 '}, {name:' File4 '}, {name:' File5 '}]);//Actual callApp.post ('/upload ', function(req,res,next) {Upload (Req,res, function(err){        if(ERR) {Req.flash (' ERROR ',' upload failed ');returnRes.redirect ('/upload '); } req.flash (' Success ',' File upload succeeded '); Res.redirect ('/'); })});

In this case, we use a modular mindset.

7, Markdown

 这个东西其实没有太多好多的,其实就是因为我们平时保存的东西可能含有一些html的格式。但是保存到数据库然后输出出来的时候,系统可能无法识别,就要转化一下
varrequire(‘markdown‘).markdown;doc.post = markdown.toHTML(doc.post);

And then it needs to be done in front of the output.

<%- post %>

So that we can identify the HTML tags.

8, Mongoose

The database used in this project is MongoDB, in fact, I am also the first contact with MongoDB, probably understand, is a between the relational database (MySQL) and non-relational database (Redis) a database, the supporting data structure is many, also very loose, A bit like JSON, and the query language is very powerful, many of node's projects use it, the book is used in the original writing, such as the following

  //Open DatabaseMongodb.open ( function (err, db) {    if(ERR) {returnCallback (ERR); }//Read posts collectionDb.collection (' posts ', function (err, collection) {      if(ERR) {Mongodb.close ();returnCallback (ERR); }//Search by user name, publication date and article nameCollection.findone ({"Name": Name,"Time.day": Day,"title": Title}, function (err, doc) {        if(ERR) {Mongodb.close ();returnCallback (ERR);    }      });  }); });

I just want to query a data, and open and close too troublesome, behind the discovery of this mongoose, found that the use is very simple, is to save the time, need to tidy up the concept

Link I wrote a db.js.

var  Mongoose = require  ( ' Mongoose ' ); var  Schema = Mongoose. Schema; var  ObjectId = Schema.objectid; var  url =  ' Mongodb://localhost/blog ' ; Mongoose.connect (URL); var  db = Mongoose.connection;db.on ( ' error ' , Console.error.bind (Console, ' connection error: ' ) ';d b.once ( ' open ' , function   ( Callback)  { //the first time you open a record, here you can write some links on the subsequent information }); module.exports = {Db:d B, Schema:schema, Mongoose:mongoose,};  

And then when you use it,

varMongoDB =require('./db ');varSchema = MongoDB. Schema;vardb = Mongodb.db;//This is similar to the field where we want to define the good one database, and we also need to initialize the database you are working on.varPostschema =NewSchema ({name:String, Title:String, Post:String, Tags: [], Comments: [], PV: {type: Number,default:0}, Reprint_info: {reprint_to: [{name:String, head:String}], Reprint_from: {name:String, Title:String, Day:String}}, Time: {date: {type:Date,default:Date. Now}, Year:String, Month:String, Day:String, minute:String,    },});

This instantiates the object, and you can use the model to manipulate the database (without saving. Save ())

var PostModel = db.model(‘post‘,PostSchema);//使用方法,对比上面那一段,这里简直简洁太多了PostModel.find({}).sort(‘-_id‘).exec(function (err, rs) {    if (err) {        return callback(err);    }    callback(null,rs);})

But to focus on the way to save the data, first of all, we have to assign values to the model defined above, which is the data I have in the project, the actual use to actually write

varnew PostModel({    name  this.name ,    time  : time ,    this.title ,    post  this.post ,    tags  this.tags});

And then save it.

postEntity.save(function(err , rs) {    if (err) {        return callback(err);    }    callback(null , rs[0]);})

This is just some basic query and insert, there are updates and deletions distinct, and so on a series of methods, but also need to study well. Official documents
Https://github.com/Automattic/mongoose

The whole project learning is a feeling, node development quickly, do the page is very convenient, but temporarily did not feel the advantages of asynchrony, after all, this project is just a starter project, understand some basic operations, there is a feeling that English is really important, Because this node in the domestic development time is not very long, so the documentation is in English, it seems to be very painful.

Blog program ideas built with node. JS (node. js Real-School reading note 1)

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.