Nodejs Tutorial The production of a simple article publishing system _node.js

Source: Internet
Author: User
Tags add time getdate mongodb

Objective

We are today to do a simple press release system, the first phase of the system does not need to be too difficult, mainly has the following functions

① News Type Management

② News Management (with image upload function)

③ News View

Although the function is not much, but also covers a lot of basic operations, the program but the addition and deletion check, plus upload attachment, enough. So let's start our study today.

Preparatory work

According to yesterday's toss, we have a nodejs and MONGODB environment, now directly new project files and database files can be

The first step is to open the command switch to the D disk after entering

Copy Code code as follows:
D:\>EXPRESS-E News

So the system will automatically be happy to build the basic environment

Obviously, many of the modules are not dependent on, this time will be yesterday's Package.json direct test come over:

Copy Code code as follows:

{
"Name": "Application-name",
"Version": "0.0.1",
' Private ': true,
"Scripts": {
"Start": "Node App.js"
},
"Dependencies": {
"Express": "3.4.8",
"Ejs": "*",
"MongoDB": "*"
}
}

Then switch to the project directory:

Copy Code code as follows:
NMP Install

The dependent files are all down, and then we enter

Copy Code code as follows:

D:\news>node app
Express Server listening on port 3000



So, our program happily run up, open the Web site A look, really no problem

PS: Here is a problem to note that we download the file is not UTF-8 code, so the Chinese may have garbled, file coding needs your own unified

When the program runs, it needs a database-related configuration.

① First new News folder in MongoDB directory

② new configuration file for Project Settings.js

Copy Code code as follows:

Module.exports = {
Cookiesecret: ' Mynews ',
DB: ' News ',
Host: ' localhost '
};

③ New models directory, new Db.js

Copy Code code 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});

④ new News.bat Program on desktop

Copy Code code as follows:
D:\mongodb\bin\mongod.exe-dbpath D:\mongodb\news

To start the database in the future, only need to run him, so that our preliminary preparation work basically ends

But here are two annoying things, one is every time to start the news program is annoying, two is to modify everything need to restart, so we here to solve these two problems

① new News_app.bat on the desktop, and then he can start the program.

Copy Code code as follows:
Node D:\news\app

②supervisor for a process saver, we can use him to help us restart the program, first follow, then adjust our Node_app.bat

Copy Code code as follows:
Supervisor D:\news\app

Of course before you need to install:

Copy Code code as follows:
NPM install-g Supervisor

This way, the file is modified without a manual reboot (you need to put the News_app in the project directory), so the preparations are done.

Project structure

When the first step is over, we need to think about the project structure.

① Home for index here will list all news types as well as for news items

② Individual news items have edit/delete/view three buttons

③ homepage with ADD News button (add time can upload picture)

Basic functions as above

So, we get rid of the routing function inside the app, and put all the routes in the index.

Copy Code code as follows:

Put the routing function into index
App.get ('/', routes.index);
App.get ('/users ', user.list);
Routes (app);

Copy Code code as follows:

Module.exports = function (APP) {
Homepage, now also home
App.get ('/', function (req, res) {
Res.render (' index ', {title: ' Express '});
});
App.get ('/add ', function (req, res) {
Res.send (' Add press request ');
});
App.get ('/delete ', function (req, res) {
Res.send (' Delete news request ');
});
App.get ('/view ', function (req, res) {
Res.send (' View news request ');
});
App.get ('/update ', function (req, res) {
Res.send (' Modify news request ');
});
};

The first step is simple, because the increase in the news should have a separate page, and the specific click on the increase button will have other processing, so the internal still have to subdivide the various requests, now stipulates as follows:

/default page, which displays all types and news, with the delete button

/add into the Add News page

/addnews Add news specific POST request address (click button Response)

/delete Delete a news request

/view Specific News Inquiries

The above routing is modified slightly:

Copy Code code as follows:

Module.exports = function (APP) {
Homepage, now also home
App.get ('/', function (req, res) {
Res.render (' index ', {title: ' Express '});
});
App.get ('/add ', function (req, res) {
Res.send (' Add News page ');
});
App.post ('/addnews ', function (req, res) {
Res.send (' Process add news request ');
});
App.get ('/delete ', function (req, res) {
Res.send (' Delete news request ');
});
App.get ('/view ', function (req, res) {
Res.send (' View news request ');
});
};

So we need to create a few new templates to organize our web page, where we will not separate the first and foremost as long as the simplest page can

Add and view two template files, temporarily appear consistent with Index.ejs, and modify navigation related

Copy Code code as follows:

Module.exports = function (APP) {
Homepage, now also home
App.get ('/', function (req, res) {
Res.render (' index ', {title: ' Express '});
});
App.get ('/add ', function (req, res) {
Res.render (' Add ', {title: ' Adding News Page '});
});
App.post ('/addnews ', function (req, res) {
Res.send (' Process add news request ');
});
App.get ('/delete ', function (req, res) {
Res.send (' Delete news request ');
});
App.get ('/view ', function (req, res) {
Res.render (' View ', {title: ' See News Request '});
});
};

End of project structure

Data manipulation

When the whole structure comes out, we need to do data manipulation:

① Add data (add News)

② display data (show news)

③ Delete data (delete news)

Originally related to the type of operation, but do to do to do not, temporarily ignore him, because the first time it is easy to get confused

Add News

Here, we don't use the form submission, we use Ajax ... This is the way to introduce the Zepto library, so our page becomes

Copy Code code as follows:



<! DOCTYPE html>


<html>


<head>


<title>


<%= title%></title>


<link rel= ' stylesheet ' href= '/stylesheets/style.css '/>


<script src= "Javascripts/zepto.js" type= "Text/javascript" ></script>


</head>


<body>


<h1>


<%= title%></h1>


<div>


Title: <input type= "text" id= "title"/>


</div>


<div>


Content £ <textarea id= "content" ></textarea>


</div>


<div>


<input type= "button" type= "button" id= "OK" value= "Add News"/>


</div>


<script type= "Text/javascript" >


$ (document). Ready (function () {


$ (' #ok '). Click (function () {


var param = {};


Param.title = $ (' #title '). Val ();


Param.content = $ (' #content '). Val ();


$.post ('/addnews ', param, function () {


Console.log (' Add success ');


});


});


});


</script>


</body>


</html>


Although there is no response to the request, so the data will not be processed, and we do not have the attachment here (now the attachment allows only a good), and then modify the code, add a picture:

PS: The more troublesome is the picture after the Ajax processing a bit of trouble, so we obediently here to change the form of the operation, or how long ...

Copy Code code as follows:



<html>


<head>


<title>


<%= title%></title>


<link rel= ' stylesheet ' href= '/stylesheets/style.css '/>


</head>


<body>


<h1>


<%= title%></h1>


<form enctype= "Multipart/form-data" method= "post" action= "/addnews" >


<div>


Title: <input type= "text" id= "title" Name= "title"/>


</div>


<div>


Photo: <input type= "file" id= "pic" name= "pic"/>


</div>


<div>


Content: <textarea id= "Content" name= "content" ></textarea>


</div>


<div>


<input type= "Submit" id= "OK" value= "Add News"/>


</div>


</form>


</body>


</html>


This appearance does not need to consider the attachment problem too much, first of all, for the time being, now process the requestor first, here in public the new News folder is used to store its pictures

Model

Add news.js files to the Models folder, build the entities for them, and give new query-related actions:

Copy Code code as follows:



var MongoDB = require ('./db ');

function News (title, Content, pic) {


This.title = title;


this.content = content;


This.pic = pic;//Save Storage Path


};


Module.exports = News;


Storing data


News.prototype = {


Save:function (callback) {


var date = new Date ();


var time = {


Date:date,


Year:date.getFullYear (),


Month:date.getFullYear () + "-" + (Date.getmonth () + 1),


Day:date.getFullYear () + "-" + (Date.getmonth () + 1) + "-" + date.getdate (),


Minute:date.getFullYear () + "-" + (Date.getmonth () + 1) + "-" + date.getdate () + "" +


Date.gethours () + ":" + (Date.getminutes () < 10? 0 ' + date.getminutes (): Date.getminutes ())


}


Data store objects


var news = {


Title:this.title,


Content:this.content,


Pic:this.pic,//photo processing in the end, let's go.


Time:time


};


Open data connection, Open is a callback ...


Mongodb.open (function (err, db) {


The error is withdrawn


if (err) {


Return callback (ERR);


}


Open News Collection


Db.collection (' News ', function (err, collection) {


if (err) {


Mongodb.close ();


Return callback (ERR);


}


Write collection (write to database)


Collection.insert (news, {safe:true}, function (err) {


Return callback (ERR);


});


callback (null);//err NULL


});


});


}


};


So, the program to write to the database, here we will try to insert the database, of course, need to modify the routing of the Program

PS: Routing Of course can not write too much logic code, this file will have to separate

This time/addnews logic needs to change.

Copy Code code as follows:

App.post ('/addnews ', function (req, res) {
var title = Req.body.title;
var content = Req.body.content;
var pic = req.body.pic;
var news = new News (title, content, pic)
News.save (function (err, data) {
Res.send (data);
})
});

Query, the problem is not big, now to solve is the attachment problem

Upload pictures

Upload picture function Express itself is supported, express through Bodyparser resolution request body, then can upload file through him, its internal use formidable

Here the App.use (Express.bodyparser ()) in App.js is changed to read:

Copy Code code as follows:
App.use (Express.bodyparser ({keepextensions:true, Uploaddir: './public/news '});

Open Index.js, preceded by a line of code:

Copy Code code as follows:
FS = require (' FS '),

Modify the index file:

Copy Code code as follows:



App.post ('/addnews ', function (req, res) {


for (var i in req.files) {


if (req.files[i] = = 0) {


To delete a file synchronously


Fs.unlinksync (Req.files[i].path);


Console.log (' success removed an empty file ');


} else {


var path = './public/news/' + req.files[i].name;


To rename a file by using the synchronization method


Fs.renamesync (Req.files[i].path, path);


Console.log (' sunccess renamed a file ');


}


}


var title = Req.body.title;


var content = Req.body.content;


var pic = req.body.pic;


var news = new News (title, content, pic)


News.save (function (err, data) {


Res.send (data);


//    })


});


This time select files and click Add News, our files are uploaded up

This time, I just need to record the file name in the database, the file directory there are pictures

Copy Code code as follows:



App.post ('/addnews ', function (req, res) {


var pic = null;


for (var i in req.files) {


if (req.files[i] = = 0) {


To delete a file synchronously


Fs.unlinksync (Req.files[i].path);


Console.log (' success removed an empty file ');


} else {


var path = './public/news/' + req.files[i].name;


To rename a file by using the synchronization method


Fs.renamesync (Req.files[i].path, path);


Console.log (' sunccess renamed a file ');


}


pic = Req.files[i].name;


}


var title = Req.body.title;


var content = Req.body.content;


var news = new News (title, content, pic)


News.save (function (err, data) {


Res.send (data);


})


Res.send (' <a href= "./" > Request successful, return home </a> '); "


});


There is data in the database, we have files in our catalogue, now we just need to read out the data.

PS: The holiday brothers urged the fierce, to go out for a drink

Reading data

The second step is of course to read the data, first of all the data read the home page:

Copy Code code as follows:



var MongoDB = require ('./db ');


function News (title, Content, pic) {


This.title = title;


this.content = content;


This.pic = pic;//Save Storage Path


};


Module.exports = News;


Storing data


News.prototype = {


Save:function (callback) {


var date = new Date ();


Data store objects


var news = {


Title:this.title,


Content:this.content,


Pic:this.pic,//photo processing in the end, let's go.


Date:date


};


Open data connection, Open is a callback ...


Mongodb.open (function (err, db) {


The error is withdrawn


if (err) {


Return callback (ERR);


}


Open News Collection


Db.collection (' News ', function (err, collection) {


if (err) {


Mongodb.close ();


Return callback (ERR);


}


Write collection (write to database)


Collection.insert (news, {safe:true}, function (err) {


Return callback (ERR);


});


callback (NULL); ERR is null


});


});


}


};


Reading articles and their related information


News.get = function (ID, callback) {


Open Database


Mongodb.open (function (err, db) {


if (err) {


Return callback (ERR);


}


Db.collection (' News ', function (err, collection) {


if (err) {


Mongodb.close ();


Return callback (ERR);


}


var query = {};


if (ID) {


Query.id = ID;


}


Querying for articles based on query object


Collection.find (query). Sort ({


Date:-1


}). ToArray (function (err, data) {


Mongodb.close ();


if (err) {


Return callback (ERR); Failed! Back to err


}


Callback (null, data); Success! Returns the results of a query as an array


});


});


});


};


News.js


Copy Code code as follows:



<! DOCTYPE html>


<html>


<head>


<title>


<%= title%></title>


<link rel= ' stylesheet ' href= '/stylesheets/style.css '/>


</head>


<body>


<h1>


<%= title%></h1>


<ul>


<%for (var k in data) {%>


<li>


<div>


Title: <%=data[k].title%></div>


<div>


Content: <%=data[k].content%></div>


<div>


Annex: <img src= "news/<%= data[k].pic%>"/></div>


</div>


<div>


<a href= "/delete?id=<%=data[k]%>" > Delete </a>


</div>


<hr/>


</li>


<%}%>


</ul>


</body>


</html>


Conclusion

Well, the article release system to the production of the first here, we will gradually increase the function, and gradually landscaping.

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.