This article is changed from Feiyu's "[Translation] Getting Started Guide for Front-end Developers, building Node.js, Express, Jade, Mongodb Server from scratch. The reason why Jade was replaced with Ejs is because I think ejs is more in line with the habits of WEB programmers, or rather, it should be more in line with the use habits of PHP and ASP programmers. OK, let’s not talk much, just start the tutorial.
Part 1 Installation in 15 minutes
If you really learn from scratch, take some time to build the environment first. It's not difficult, I'm using Win8, so this looks a bit different from those tutorials using Mac and Ubuntu or other *nix systems, but it's roughly the same.
Step 1 Install Node.JS
It's easy to go to the official Node.js website and click on the green big Install button, which will automatically detect your system and give you a download of the correct installation file. (If not, click the Download button to select the download you need). Run the installer, and that's fine. You have installed Node.js and NPM (Node Package Manager) to easily install various useful packages into Node.
Step 2 Install Express
Now that we have let Node run, we need something else to allow us to actually create a site that is available. Next we need to install Express, which is a framework that turns Node from an original application to a more similar web server we usually use. We need to start with Express because we need the scaffolding functionality it provides. Let's enter this command:
The code copy is as follows:
c:/node>npm install -g express
In this way, Express is correctly installed into our Node and has been set to globally available. You will see a bunch of output in the command line window, mostly http 304 and GET requests, which is normal. Express should be installed and available.
Step 3 Create an Express Project
We are going to use Express and Ejs, but not for CSS preprocessing. We will hand-written some CSS. We need to use Ejs or other template engines to process Node and Express data. If you know HTML, Ejs is not difficult. Just remember that you need to focus or things can be prone to errors.
Now enter in the same command line window:
The code copy is as follows:
c:/node>express sessions nodetest1
Enter and you will see a bunch of things like this:
The code copy is as follows:
C:/node>express --sessions nodetest1
create : nodetest1
create : nodetest1/package.json
create : nodetest1/app.js
create : nodetest1/routes
create : nodetest1/routes/index.js
create : nodetest1/routes/user.js
create : nodetest1/views
create : nodetest1/views/index.ejs
create : nodetest1/public/images
create : nodetest1/public/javascripts
create : nodetest1/public
create : nodetest1/public/stylesheets
create : nodetest1/public/stylesheets/style.css
install dependencies:
$ cd nodetest1 && npm install
run the app:
$ node app
Step 4 Edit Dependencies
OK, we have some basic project structures now, but it's not finished yet. You will notice that the installation process of express creates a file called package.json in your nodetest1 directory. Open the file with a text editor. It should look like this.
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": "*"
}
}
This is a standard JSON format file that indicates our application and its dependencies. We need to add something. For example, calls to mongodb and Monk. Change the dependencies part to this:
The code copy is as follows:
"dependencies": {
"express": "3.4.8",
"ejs": "*",
"mongodb": "*",
"monk": "*"
}
Step 5 Install Dependencies
Now we have defined the dependencies of the project. * will tell NPM to "install the latest version". Return to the command line window, enter the nodetest1 directory, and enter:
The code copy is as follows:
C:/node/nodetest1>npm install
It outputs a bunch of things. This is because it directly reads our modified JSON file, recognizes the dependencies in it, and installs the required files. After the NPM installation is complete, you should have a node_modules directory containing all the dependency files required for our project.
Now we have a full-featured app and it is ready to run. Let's give it a try! Make sure your current directory is the nodetest1 directory, enter:
The code copy is as follows:
C:/node/nodetest1>node app.js
After entering the car, you will see:
The code copy is as follows:
Express server listening on port 3000
marvelous. Open the browser and enter http://localhost:3000, and you should be able to see a welcome page in Express.
Now you have started running your own Node JS WebServer with Express engine and Ejs HTML template engine. Not very difficult, right?
Part 2 is here, let’s write “Hello, World!”
Open your commonly used text editor or other IDE, I personally like to use Sublime Text. Open app.js in your nodetest1 directory, and this file is the core of your app. You should see something like this:
The code copy is as follows:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
This just defines a bunch of JavaScript variables and points to some packages and dependencies, node functions, and routes. Routes is equivalent to a collection of Models and Controllers in MVC. It is responsible for forwarding requests and also contains some processing logic. Express has created all of these things for us, and we now ignore the user route and start writing the top-level route (controlled by routes/index.js).
At the end of the above file:
The code copy is as follows:
var app = express();
This sentence is crucial. It instantiates Express and assigns value to our app variable. The following content needs to use this variable to configure a bunch of Express parameters. Continue to enter:
The code copy is as follows:
// 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.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
Here we set up the port, look for the directory of views, what template engine to use to handle these views, and some other things. Also pay attention to the last line, which tells Express to host the static files in the public/ directory as files in the top-level directory. For example, your image directory is stored in c:/node/nodetest1/public/images/, but the actual access address is http://localhost:3000/images/.
Note: You need to put this line
The code copy is as follows:
app.use(express.bodyParser());
Change to
The code copy is as follows:
app.use(express.urlencoded());
This is to ignore the warning information in the Node window during the operation of some apps. Mainly some Express and its plug-in may be modified in the future. If you don't make this modification, you will receive a bunch of warnings that a certain function will expire soon when the program runs.
Then add:
The code copy is as follows:
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
This way you can do some error checks during development.
Continue to increase:
The code copy is as follows:
app.get('/', routes.index);
app.get('/users', user.list);
This will tell the route which Route to use when a URI request arrives. Note that the user variable is defined earlier and mapped to /routes/user.js. We will call the list function defined in this file. A user list can be displayed here.
Continue to increase:
The code copy is as follows:
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Finally, create an http server and start it. That's about it.
(The above content is complete in the template generated by the new express and does not need to be written in it yourself)
Now, let's write something useful. We won't write "Hello World!" directly on our index page. We will take this opportunity to learn how to use route routing and learn how the Ejs engine works. Add a line after the app.get() paragraph of the above app.js file:
app.get('/helloworld', routes.helloworld);
If you press ctrl+C in the command line window to end the app.js process and restart it, and then use the browser to access http://localhost:3000/helloworld, you will get an exciting node error and a bunch of crash prompts in the command line window. This is because we have not modified the route to process this path. Come and do this. In your editor, go to the routes directory, find index.js, and open it. It should look like this:
The code copy is as follows:
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
Let's add a new page. I prefer to create an independent route file for each first-level directory, but now we are not planning to create a complete directory structure for helloworld under views, so we use index routes for the time being. Add at the end of this file:
The code copy is as follows:
exports.helloworld = function(req, res){
res.render('helloworld', { title: 'Hello, World!' });
};
It will be responsible for handling this URI request, but now we don't have an actual page to make res.render render, which is what Ejs is responsible for. Go to your views directory, open index.ejs, and save it as helloworld.ejs file. Now it should look like this:
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>
<p>Welcome to <%= title %></p>
</body>
</html>
It should be easy to understand.
Save the file. Press ctrl+c in the command line window to interrupt app.js, and then enter node app.js to restart it. Tip: When you modify an ejs template file, you do not need to restart the server. But when you change a js file, such as app.js or a routing js file, you must restart the server to see the effect.
After the server starts, the server opens http://localhost:3000/helloworld and you should be able to see this beautiful interface:
alright! Now that we have the routes that can handle our templates, we see the effect we want. Next, let’s do some Models (data layer).
Part 3 Create a database and read data
Step 1 Install Mongodb
Let's close the text editor first and return to the command line window. First use your browser, open http://mongodb.org/, and download Mongo. Click the download link in the main menu to find the version that suits you. For 64-bit win8, download the 64-bit *2008R2+ version. After downloading, it is a zip file, and it is uncompressed to c:/mongo, c:/program files/mongo or whatever it is. This doesn't matter. We save the data in our nodetest1 directory.
Step 2 Run Mongod and Mongo
Create a subdirectory data in our nodetest1 directory, and then enter the bin directory of your mongodb directory in the command line window, and enter:
The code copy is as follows:
mongod dbpath c:/node/nodetest1/data
You will see that the mongo server is started, and the first startup takes a little time, because it requires pre-allocating some hard disk space and some other tasks. When it prompts "[initandlisten] waiting for connections on port 27017", it's done. There is nothing else to do, the server is already running. Now you need to open another command line window, enter the bin directory of the mongo directory, and enter
The code copy is as follows:
mongo
You will see some tips like this:
The code copy is as follows:
c:/mongo>mongo
MongoDB shell version: 2.4.5
connecting to: test
At this time, if you look at the mongod window, you will see a prompt that a connection has been connected. Next, we will use this command line client to manually process our database, but this is not necessary for our Web site.
Step 3 Create a database
Don't worry about the above prompt for connecting to test. That's just a database that mongo defaults when you don't specify a database, and it won't even create this database called test unless you add a record to it. Let's create our own database. In the command line window of mongo, enter:
The code copy is as follows:
use nodetest1
It will not create this database unless we insert some data into it.
Step 4 Add some data
My favorite feature of MongoDB is that it uses JSON as the data structure, which means I am very familiar with it. If you are not familiar with JSON, read some relevant materials first, which is beyond the scope of this tutorial.
We add some data to the collection. In this tutorial, we only have a simple database, two fields: username and email. Our data looks like this:
The code copy is as follows:
{
"_id" : 1234,
"username" : "cwbuecheler",
"email" : "[email protected]"
}
You can create your own value of _id field, but I think it's better to let mongo do it. It creates a unique value for each record. Let's see how it works. In the mongo window, enter:
The code copy is as follows:
db.usercollection.insert({ "username" : "testuser1", "email" : "[email protected]" })
Important tip: db is the nodetest1 database we created above, and usercollection is our collection, which is equivalent to a data table. Note that we do not need to create this collection in advance, it will be automatically created when it is used for the first time. OK, press Enter. If everything goes well, you will see... nothing. This is not very good, enter:
The code copy is as follows:
db.usercollection.find().pretty()
If you are curious, the pretty method will format the output content and add newline indentation. It should display:
The code copy is as follows:
{
"_id" : ObjectId("5202b481d2184d390cbf6eca"),
"username" : "testuser1",
"email" : "[email protected]"
}
Of course, the ObjectID you get should be different, mongo will automatically generate one. If you have used JSON interface services before, do you think, wow, calling this in the web should be very simple! Well, you're right.
Tip: As a formal service, you should not want all data to be at the top level. Regarding the design of mongodb data structure, take a look at Google.
Now that we have a piece of data, let’s add more points. Enter:
The code copy is as follows:
newsstuff = [{ "username" : "testuser2", "email" : "[email protected]" }, { "username" : "testuser3", "email" : "[email protected]" }]
db.usercollection.insert(newstuff);
Note that we pass multiple pieces of data to the collection at once through one data. How simple! Then use the find command above and you will see these three pieces of data.
Now let’s integrate the web server and database built before.
Step 5 Connect mongo to node
Now let’s create a page and display the records in the database into a beautiful table. Here is the HTML content we are preparing to generate:
The code copy is as follows:
<ul>
<li><a href="mailto:[email protected]">testuser1</a></li>
<li><a href="mailto:[email protected]">testuser2</a></li>
<li><a href="mailto:[email protected]">testuser3</a></li>
</ul>
I know this is not very scientific, but you can understand it. We are just trying to build a simple database read and write program, not a complete website. First, we add a little content to app.js (the heart and soul of our program) so that we can link mongodb. Open c:/node/nodetest1/app.js, at the top you will see:
The code copy is as follows:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
Add below it:
The code copy is as follows:
// New Code
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
These lines will tell the app that we need to connect to MongoDB. We use Monk to be responsible for this connection. Our database location is localhost:27017/nodetest1. Note that 27017 is the default port of mongodb. If you modify the port for some reason, you should also change the record here. Now look at the bottom of the file:
The code copy is as follows:
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/helloworld', routes.helloworld);
Add a line below:
The code copy is as follows:
app.get('/userlist', routes.userlist(db));
This line tells the app that when the user accesses the /userlist path, we need to pass the db variable to the userlist route. But we don't have a userlist route yet, so let's create one now.
Step 6 Read the data in mongo and display it
Use your editor to open c:/node/nodetest1/routes/idnex.js, which has two routes: index and hello world. Now let's add the third one:
The code copy is as follows:
exports.userlist = function(db) {
return function(req, res) {
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
};
};
Well, things get a little complicated. Here we first define a function, receive the db variable we pass, and then call a page render that is the same as the previous two routes. We tell it that we need to read the usercollection, do a lookup, and the returned data is saved in the docs variable. Once we have read the content, we call render to render the userlist template page and pass the obtained docs variable as the userlist variable in the template engine.
Next, create our Ejs template. Open index.ejs in the views directory, save as userlist.ejs, and modify its HTML to this:
The code copy is as follows:
<!DOCTYPE html>
<html>
<head>
<title>USERLIST</title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>Userlist</h1>
<ul>
<%
for(var i in userlist){
%>
<li><a href=”mailto:<%=userlist[i].email%>”><%=userlist[i].username%></a></li>
<% } %>
</ul>
</body>
</html>
Save the file and restart the node server. Hope you still remember how to restart. Open the browser and visit http://localhost:3000/userlist, and you should see an interface like this:
Click the Submit button and you will see an error of "can't post to /adduser". Let's fix it.
Step 2 Create your database processing function
As before, we modify app.js, then route file, and then ejs template. However, there is no need for an ejs template here, because we will jump to post later. Add a line after the app.get() paragraph of app.js:
The code copy is as follows:
app.post('/adduser', routes.adduser(db));
Note that this is app.post, not app.get. Let's set the route. Go back to routes/index.js and create our database insert function. This is quite large, so I suggest you write a good comment.
The code copy is as follows:
exports.adduser = function(db) {
return function(req, res) {
// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;
// Set our collection
var collection = db.get('usercollection');
// Submit to the DB
collection.insert({
"username" : userName,
"email" : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// If it worked, set the header so the address bar doesn't still say /adduser
res.location("userlist");
// And forward to success page
res.redirect("userlist");
}
});
}
}
Obviously, in real projects, you still need to do a lot of verification, such as username and email do not allow duplication, and email address must comply with certain format rules. But now let's not care about these things. You can see that when the insertion database is done, we let the user jump back to the userlist page where they should see the newly inserted data.
Is this the best way?
Step 3 Connect to the database and write the data
Make sure your mongod is running! Then restart your node server. Open http://localhost:3000/newuser with your browser. Now we fill in some content and click the Submit button. If it goes well, we should go back to the userlist page and see the new data we just added.
Now we have officially completed reading and writing to the Mongodb database using Node.js, Exress, and Ejs. We are already a programmer of Niu X.
Congratulations, really. If you have finished this tutorial seriously and are very serious about learning rather than just copying the code, you should have a complete concept of routes, views, reading data, and writing data. Here are all the knowledge you need to use to develop any other complete web site! No matter what you think, I think this is really cool.
Part 5 Next Step
Now start, you have unlimited possibilities. You can take a look at Mongoose, another Node package that handles MongoDB databases. It's a little bigger than Monk and has more features. You can also take a look at Stylus, an Express CSS engine. You can Google Node Express Mongo Tutorial and see what's next. Study hard and improve every day.
I hope this tutorial helps, I wrote this because when I started learning I really needed something like this, but I really couldn't find it. If you've seen it here, thank you very much!