Node.js Express Tutorial for Beginners

node.js express tutorialThe Internet is built on millions of networks that interconnect with each other. Traditionally, you send a web request to a web server and the web server returns HTML and the JavaScript used for client-side coding. The JS sent with the web page’s HTML runs on your computer. Node.js is a revolutionary concept that lets you write server-client applications between your web users and your web server. The Node.js library lets you make network applications using your web server and JS. Your users can communicate with your users directly from the web page and you can send and receive messages real-time. All of this can happen without forcing the user to reload a web page. This makes fast, real-time network applications over the Internet.

Learn the Node.js Express library from the beginning

Getting Started with Node.js Express

Node.js is an extended library that builds off of the original Node.js project. This article assumes you have the JS libraries installed on your computer to use them. You can download the library from Github. You need Node.js Express on your server and your client application. Node.js is a server-client application library, so you’ll need to create a server application that listens for requests and a client application that sends the requests.

You need a basic JSON file to describe your application settings. The following is an example of a JSON file you need with your Node.js Express project:

{
"name": "Your App Name",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node app.js"
},
"dependencies": {
"express": "3.4.4",
"jade": "*",
"mongodb": "*"
}
}

The JSON is pretty self-explanatory. The configuration file gives the application a version, a name and any dependencies and scripts needed to run the application. In this application, the dependency is MongoDB, which is a common NoSQL database source that’s useful when developing web applications.

Learn how to work with NoSQL database design with MongoDB

Getting Started with Coding Your First Application

To get started with a basic project, you first need two variables: one variable for the application and another for the “Express” libraries. Use the following two lines of code in the beginning of your code:

var express = require('express');
var app = express();

After you create your variables, you use these variables to set up your application and its environment. The following code sets some app environments for your program:

app.set('port', process.env.PORT || 8000);
app.set('views', path.join(“/directory/”, 'views'));
app.set('view engine', 'jade');

The above code is just a few app settings. You can set several more that are defined in the Node.js Express documentation. The first app setting defines the port where your application will communicate. The second setting defines the directory for your views and the third setting defines the engine that will render the views. In this case, it’s Jade.

The next step is creating a basic command to display some text in the web browser. You can send any text using Node.js Express and the browser will display it using the view engine you defined earlier. The following code sends “This is a test” to the app engine:

app.get('/', function(req, res){
res.send(' This is a test ');
});

You also need a server to listen to requests pending for your application.  The following code sets up a server application that listens to requests on port 8081:

var server = app.listen(8081, function() {
console.log('Listening on port %d', server.address().port);
});

Notice the “console.log” expression. This is a good way to watch the actions of your server while you’re developing the application. In this instance, the console log prints out the port on which the server is listening, so you know which port is in use. This can be helpful if your application isn’t responding properly to requests.

Learn how to use JavaScript server technology with your application development

Error Handling

As much as programmers hate it, they all must do error handling when creating your programs. Error handling traps issues that you don’t foresee in your code. For instance, maybe you don’t account for null values and didn’t filter out null values. The result is your code throws an error. If you don’t have error handling, the result is a program that crashes on a user’s computer. At the worst, the user is forced to reboot the computer to get through the crashed software. You obviously don’t want this inconvenience for your users, so you use error handling to deal with issues. Node.js Express lets you deal with errors in the same way other languages deal with errors. You trap the error and return a response to the user. The goal of error handling is to account for unknown errors and respond with a window or a way for a user to cancel out of the error. You want to make your error handling as convenient as possible for the user.

The following is a basic Node.js Express function that handles an error and returns “An error has occurred. Please try again later” to the user:

app.use(function(err, req, res, next){
console.error(err.stack);
res.send(500, ‘An error has occurred. Please try again later.');
});

The above code accounts for one error, but you can create a “catch all” error handler that not only catches an error but renders an error page for the user. This can be useful if the application has a fatal error that can’t be accounted for and you need the user to go to a different page before continuing. For instance, if you have a feature that is no longer implemented but forgot to remove it from your application code, you can throw an error and send the user to another web page.

The following code send an error to the application that you can render for the user:

function errorHandler(err, req, res, next) {
res.status(500);
res.render('app_error', { error: err });
}

Connecting to a Database Such as MongoDB

No dynamic website is complete without a database to retrieve and store data. MongoDB is a free open source database you can add to your projects, and it’s a great platform for development. MongoDB doesn’t have the restrictions like traditional SQL databases, so it makes it easier for you to develop. You can port your projects over to a different platform when you finished development provided you keep your data layer separated from your application layer.

The following two lines of code retrieve a database connection:

var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/dbtest');

In this example, the database is running on the same computer as your application. In most development projects, your database is on the same computer as your development machine. However, if you happen to have a database on another server, use this address instead of “localhost.” The “27017” is the port number, so ensure you include the port with your connection if it is different than the default.

The next step is obtaining data. For instance, if you write an app that deals with customers, you might want to query the database for a list of customers. The following code obtains a list of customers and stores it in a variable:

exports.customerlist = function(db) {
return function(req, res) {
var collection = db.get('customers');
collection.find({},{},function(e,docs){
res.render('customerlist', {
"customerlist" : docs
});
});
};
};

The above function is a simple function that retrieves a list of customers from the MongoDB. MongoDB stores data differently than traditional databases. MongoDB stores objects called documents and these documents can have any number of data in them. There are no restrictions like relational databases that tell you what types of data you can store. Node.js Express can work with these documents and display them on your web pages.

This basic tutorial helps you understand the Node.js Express basic libraries, but you can extend this basic knowledge to powerful applications that perform real-time actions for your users. The real-time activity makes these applications faster and more useful for users. You can replace old desktop software for server-client applications that work just like a desktop application that connects to a central server. However, with Node.js Express, these applications are faster, easier to use and take up less memory on the user’s computer.

The best starting point is learning JavaScript and then downloading the JS libraries. What’s great is that you don’t need a physical server and client computer. Instead, your computer can act as both the server and client while you develop your application.

Get a full course on Node.js and developing powerful apps at Udemy.com