Programming Tutorials

  • View all tutorials
  • Get started with Node.js and Express
    Node.js is a server-side platform built on Google Chrome's JavaScript V8 engine. It allows you to build fast and scalable network applications that are written in JavaScript and can be run on OS X, Linux, and Microsoft Windows. Before Node.js was released in 2009, applications on the web had their server-side code written in languages like PHP, Perl, Python, Java, and others, but it is now possible to use JavaScript on the front-end and back-end entirely, meaning that you can run JavaScript code outside of the browser now. Some notable companies, like Netflix, PayPal, GoDaddy, and IBM, currently use Node.js to power their software.

    Installing Node.js and Express

    In this tutorial we're going to cover how to get started on an application using Node.js and the Express framework. Express is the de facto standard server framework for Node.js, and it allows you to easily structure and separate different parts of your code, setup HTTP routing, integrate a template engine, and integrate several other features. To install Node.js, go to the download page and download and run the installer for the operating system you're currently using. Once it's installed, create a new folder anywhere you want and call it node_app. Node.js comes with something called npm, which is Node's default package manager. It allows you to easily install JavaScript applications and modules that people make available on the registry. This makes it easy to install Express now. First, open your terminal (or command prompt) and go into the directory you created above called node_app. Once you're in that directory, run the following command:
    npm install express
    
    This will install Express in a folder called node_modules. Then go ahead and create an app.js file in the main directory. Your node_app directory should look like this now: For more information or help installing Express you can check out this resource.

    Creating the server

    We're going to create a simple server and route some pages. Open app.js and add the following code to the file:
    var express = require('express');
    var app = express();
    
    // route pages
    app.get('/', function (req, res) {
      res.send('Main page is up and running!');
    });
    
    app.get('/user', function (req, res) {
      res.send('TODO: update this page...');
    });
    
    // what port to run server on
    app.listen(3001, function () {
      console.log('server started on port 3001');
    });
    
    To test this code, in the terminal run the following command:
    node app.js
    
    Now if you open a web browser and go to the url: 127.0.0.1:3001, you should see the following on your screen: You can also go to the user page you setup as a router by going to: 127.0.0.1:3001/user, and you should see the following on the page: Let's setup our user page to work properly now, so that when a user's name is entered in the URL, we'll display that user's information on the page. We'll update the user router to check for a query parameter, and we'll create an object that will store all the information we need. Update your app.js file to the following code:
    var express = require('express');
    var app = express();
    
    // you can make a request to a database here and retrieve some data
    // but for this example, we are using a static object of user information
    var Users = {
    
      'David': {
        age: 52,
        occupation: 'Professor',
        hobby: 'Swimming'
      },
    
      'Robert': {
        age: 34,
        occupation: 'Engineer',
        hobby: 'Running'
      },
    
      'Jane': {
        age: 28,
        occupation: 'Nurse',
        hobby: 'Chess'
      }
    
    };
    
    // route pages
    app.get('/', function (req, res) {
      res.send('Main page is up and running!');
    });
    
    app.get('/user', function (req, res) {
      var check = Users[req.query.name];
      var info = (check) ? check : 'User does not exist...';
      res.send(info);
    });
    
    // what port to run server on
    app.listen(3001, function () {
      console.log('server started on port 3001');
    });
    
    If you restart your server now (press CTRL + C) and rerun the app.js file, you can now enter in a query parameter called name in the url to retrieve a user's information. Below is an example:

    Template engine

    What you'll most likely want to do is actually display an HTML page with some information in it, rather than display an object on the web page. We're going to install a template engine called EJS, which will allow us to render an HTML page and add in some variables that we send in from the server, such as user info. First, stop the server in your terminal by pressing CTRL + C, and then run the following command to install EJS:
    npm install ejs
    
    This will install the EJS module in your node_modules directory. Next, create a new folder in your node_app directory and call it views, and in this folder create a blank file called user.ejs. Your app directory should look like this now: What we want to do now is render an HTML page, and pass some variables to it that we can then insert somewhere into the HTML page for users to see. In app.js we'll add the following statement at the top of the file to let our app know we are using EJS as a template engine.
    var express = require('express');
    var app = express();
    app.set('view engine', 'ejs');
    
    Now, in the route section replace the user route code with the following new code:
    app.get('/user', function (req, res) {
      var check = Users[req.query.name];
      if (check) {
        res.render('user', { name: req.query.name, info: check });
      } else {
        res.send('User does not exist...');
      }
    });
    
    What's happening now is, when someone attempts to view the user page, if the name query parameter exists and is a valid user then we pass in the variables name and info to the user.ejs file, otherwise simply display an error message. Now finally we will setup our HTML page. Open the user.ejs file and enter in the following code:
    <!DOCTYPE html>  
    <html>  
    <head>
      <meta charset="utf-8">
      <title>User page</title>
    </head>
    <body>
      <h1> Profile: <%= name %> </h1>
      <ul>
        <li> <b>Age:</b> <%= info.age %> years old </li>
        <li> <b>Occupation:</b> <%= info.occupation %> </li>
        <li> <b>Hobby is:</b> <%= info.hobby %> </li>
      </ul>
    </body>
    </html>  
    
    The <%= %> tags output JavaScript values directly into the HTML. There are two variables being passed into this template: name which is the user's name and info is a JavaScript object that contains user information. If we open up the user page with a query parameter, we should see this page now:

    Final index page

    Let's tie together our home page and user page now. We'll display all users on the home page, and then when a user is clicked their profile will be displayed. Replace the main route code in app.js with the following code:
    app.get('/', function (req, res) {
      var usersArray = [];
      for (var i in Users) { usersArray.push(i); }
      res.render('index', { users: usersArray });
    });
    
    Now create a new file in the views folder and name it index.ejs. In this new file, add the following code to render an HTML page and loop through the users array, displaying each user.
    <!DOCTYPE html>  
    <html>  
    <head>
      <meta charset="utf-8">
      <title>User page</title>
    </head>
    <body>
      <h1>Users</h1>
      <ul>
        <% for (var i = 0; i < users.length; i++) { %>
        <li> <a href="/user?name=<%= users[i] %>"><%= users[i] %></a> </li>
        <% } %>
      </ul>
    </body>
    </html>  
    
    As you can see in the EJS file, you can also create a for loop similar to how you would in JavaScript, except you place the code between <% %> tags. Now if you restart your server and open the index page, you should see the following:

    Conclusion

    In this tutorial we learned how to install Node.js, Express, EJS, setup a proper directory structure, and run a local server. We created two simple pages that listed users and displayed their information. In upcoming tutorials we'll cover how to connect to a database using Node.js, and how to incorporate other helpful libraries that aid in building web applications with Node.js. For more information on Node.js you can check out these resources: TutorialsPoint Guide Express Tutorials Top 10 Mistakes Node.js Developers Make The Art of Node
    mrdaniel wrote this tutorial on 5/13/16 | javascript, nodejs, express
    Comments
  • +
  • 4
  • -
  • simple and beautiful, perfect for beginners.
  • +
  • 1
  • -
  • @hanmhs9, on windows or mac if you create a blank new file, you can simply call your file "user.ejs" and it will save the file with that extension. You don't need any special program to create a file with that extension.
  • +
  • 1
  • -
  • how do i create a blnak file called user.ejs? There's no such instruction or way to create a file with extension ejs
  • +
  • 0
  • -
  • Do you have to define app?
  • +
  • 0
  • -
  • @mrdaniel yeah so how do you 'create a blank new file'? Is that supposed to be the right click->new->text document and name it "user.ejs"? I can't find anything called 'File' in the 'new' category except text documents, folder, word doc, excel, etc but no 'FILE'.
    Log in to submit a comment.