Node.js | Express Framework
Framework Benefits and Express
So far, we have explained how to handle the basic features of a web application. To be honest, you may have felt that it was more troublesome than expected.
Why a Framework Is Needed
Whatever you want to do, you have to write every small detail yourself. By introducing EJS, you were able to use templates, but you still had to preload template files and write the rendering process yourself. If you need to prepare multiple pages, you also have to create your own URL-based routing process. For POST data, you must use events to gather all the data, decode it, and make the required values available. With this approach, you may lose the motivation to create complex web applications with many pages.
Most of this work is also “required for any web application.” If so, development would become much easier if the features used by web applications were implemented in advance and a basic system for web applications were prepared.
The result of this idea is what is generally called a “web application framework.” It is not simply a library that collects features, but a program that provides the basic system of a web application itself.
Express Framework
Node.js also provides web application frameworks. Among them, the most widely used is Express.
Like EJS, Express is provided as a Node.js package. You can install it easily with npm and create a server program that integrates it. Because EJS can be used as the template engine, the EJS templates created so far can also be reused as-is.
Express has a basic system for web applications, and you add the necessary processing to it. The basic development style of integrating event processing is the same as when implementing only with Node.js, but you can combine the prepared objects very easily to create the processing you need.
The Express site is below. Documentation is also available there. Because npm is used, you do not need to download library files from the site.
Creating a Web Application with Express
Now let us actually use Express. To use Express, first install it with npm. Start Command Prompt, or Terminal on Mac OS X.
When installing Express, you need to think about “where to install Express.” There are two options.
Installing as a Node.js Module
Install it as a module in the Node.js body. This lets any web application use it. However, when deploying the application to a server, it will not work if Express is not installed on that server.
Installing it as a Node.js module is simple. As with EJS, run the following command in Command Prompt.
$ npm install express
Installing in the Web Application Folder
With this method, you must install it every time you create an application. However, because all files are included in the application, the application works without problems even if the server does not have Express installed.
If you plan to deploy the application you create, it is better to install all modules required by the application. Here, let us create a simple application with that approach. Proceed with the following steps.
1. Prepare the application folder.
First, prepare a folder for the application. Here, we will prepare a folder named expressapp on the desktop.
If you are using Command Prompt, move to a suitable folder with cd, then run the following command to create the folder.
mkdir expressapp
2. Move to the folder in Command Prompt.
Start Command Prompt, or Terminal on Mac OS X. Then use the cd command to move to the expressapp folder.
3. Initialize npm.
Initialize npm by running the following command.
npm init
When it runs, it asks for the name, version, description, entry point, test command, Git repository, keywords, author, license, and so on. If you are not sure, press Enter for all of them. This creates a package.json file.
4. Install Express.
Install Express by running the following command.
npm install express --save
Now a folder named node_modules is created in the expressapp application, and a folder named express is stored inside it. This is the folder where the Express files are stored.
5. Install EJS.
Next, install EJS, which is used as the template engine in Express. Again, use npm and run the following command.
npm install ejs
This creates an ejs folder inside node_modules, and the files are stored there.
Now the preparation for creating a web application is complete. After this, add concrete code such as scripts and templates to build the application.
Basic Script Using Express
Now let us write the application script using Express. First, consider the most basic script that uses Express.
Writing the Basic Script
Use a text editor to write the following script. Save it as app.js in the expressapp folder prepared earlier.
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.send('Hello World!');
})
var server = app.listen(3000, function(){
console.log('Server is running!');
})
After saving it, move to the folder containing this app.js, the expressapp folder, in Command Prompt, and run:
node app.js
Then visit the following address in a browser.
The text “Hello World!” is displayed on the screen. This is still a simple example that outputs only text, not a template, but the basic script for an application using Express is complete.
Summary of Basic Express Processing
In this example, because Express is used, the way the script is written has changed. Let us summarize the key points.
Loading Express
var express = require('express');
First, load the Express library. This can be done with require('express'), and the loaded variable express is used to access Express features.
Creating an Express Application Object
var app = express();
The first thing to do is prepare the application object. This calls the express function. This function creates and returns an Express Application object.
Registering GET
app.get("/", function(req, res){...omitted...});
Next, register GET processing. This registers access by HTTP GET. The first argument specifies the access path, and the second argument specifies the function to execute. When there is access to the path in the first argument, the function in the second argument is called.
The callback function in the second argument receives request and response objects as arguments. These are the request and response objects you already know.
If you register functions for as many access paths as needed with this get method, you can add any number of pages. This eliminates the need for troublesome routing processing.
Listening on a Port
app.listen(3000, function(){...omitted...});
Finally, specify a port number and call listen. This starts waiting on the specified port number. You can also prepare processing after listening starts by using a callback function.
This completes the server startup process. After this, whenever access occurs on a specified path, the corresponding processing is executed.
Compared with creating it using only Node.js, the script is clean enough. Express allows you to create web applications efficiently.
Using Templates in Express
Now that we roughly understand the basic flow of processing with Express, let us display content using templates. Prepare a template file and modify the app.js script.
Preparing the Template
First, create the template. This time, create it with the file name test.ejs. The source code is shown below.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title><%=title %></title>
<style>
body { font-size:12pt; color:#000066; }
h1 { font-size:18pt; background-color:#DDDDFF; }
pre { background-color:#EEEEEE; }
</style>
</head>
<body>
<header>
<h1><%=title %></h1>
</header>
<article>
<%-content %>
</article>
</body>
</html>
Do not place the test.ejs file directly in the web application folder. Prepare a new folder named views in the web application folder, and put test.ejs in that folder.
In Express, templates related to screen display are organized in the views folder like this. The installation location and folder name can be changed, but the default is the views folder, so we use it as-is here.
The template we created is basically almost the same as the EJS template used earlier.
Here, the header and body have the <%=title %> tag for outputting a title and the <%-content %> tag for displaying content. In the Node.js script, prepare processing that passes values to variables such as title and content output by these tags.
Processing with the Template
Now let us write the Node.js script. Write app.js as follows.
var express = require('express');
var ejs = require("ejs");
var app = express();
app.engine('ejs', ejs.renderFile);
app.get("/", function(req, res){
res.render('test.ejs', {title: 'Test Page', content: 'this is test.'});
});
var server = app.listen(3000, function(){
console.log('Server is running!');
})
Start the server again with node app.js, then access localhost:3000. The rendered template display should appear.
Key Points of Template Use
Now EJS template functionality works properly in Express. Let us check the changes.
Loading EJS
var ejs = require("ejs");
First, load EJS with require. This should already be a familiar task.
Setting the Template Engine
app.engine('ejs', ejs.renderFile);
Set the template engine. This uses the engine method of the Application object. The first argument is the template file extension, and the second argument sets the template engine callback function. This callback function is set to the renderFile property of the ejs object. This completes the template engine setting.
Preparing the GET Callback Function
What is performed inside the callback function is page display using the EJS template. It calls the render method of the response.
res.render( templateFile, object );
The first argument specifies the template file name to use. The second argument specifies an associative array where the variable names passed to the template are keys and their values are combined. This renders the page.
Be careful about the template file name. It must be stored in the views folder. You do not need to write the path to the views folder such as views/test.ejs; specify only the file name test.ejs.
Express automatically searches for files in the views folder. Conversely, if the file is in the application folder instead of the views folder, it will not be found and an error will occur.
Now we understand the basics of an application using Express. Once you know how to use it, the whole structure becomes more organized and easier to understand than using Node.js alone.