Introduction To Express

Yes, we know that node.js provides us with the JavaScript runtime to execute server-side code. That's good! That means we can design and implement some good console apps which can leverage the node.js runtime. But is it all that we want this great JavaScript runtime environment to offer? Of course not!

Yes, it's always better to give a bit of facelift to any existing entity. In the context of this blog, let us try to give this plain and simple server side code a chance to run within the confines of a web application rather than just playing around with the console.

Let's get started. First things first; for any developer working his way around to build a web application, he needs to simulate a web server type environment on his machine to make sure that the code he writes is actually building the right thing. To be able to test the functionality as well as to get a first hand taste of the UI components that would ultimately form and enhance the beauty of his web application.

With web applications leveraging node.js, things are no different. But yes, things do get a little bit easier for us developers whenever there is some piece of art readily available to save our time and effort. And the Express framework does exactly that.

Express is a node.js web application framework providing a robust set of features for building single, multipage and hybrid web applications. To put it simply, it offers just about the right infrastructure to make that code of ours execute inside the comforts of a web server. Without much ado, let's get down to how to set up Express in your potential web based node.js application.

npm install express --save

Type in the above command in the command line with the current directory being set to the application root.

This shall install Express framework to your application and register it to the set of dependencies defined in the
package.json file.

Next, we shall create a file that will handle all the Express related functionalities in the application. Let's name this file as server.js,
  1. --server.js code  
  2. const express = require("express");  
  3. var app = express();  
  4. app.get("/", (req, res) => {  
  5.     res.send("Hello World");  
  6. });  
  7. app.get("/books", (req, res) => {  
  8.     res.send({  
  9.         message: "Hello Books"  
  10.     });  
  11. })  
  12. app.listen(3000, () => {  
  13.     console.log("The web server is up and running!");  
  14. });  
Let's take a deep look on the code presented above,
  1. const express = require("express");  
This code simply adds a reference to the Express framework and stores in a constant called "express" .
  1. var app = express();  
This fires up an instance of the Express server.
  1. app.get("/",(req,res)=>{  
  2.    res.send("Hello World");  
  3. });  
This is where the real thing starts. Here, we define an Express route that instructs the server what response to send if it receives a request with a particular URL. The first argument denotes the url path and the second argument is a function that contains both the request and response parameters for working with a particular request. In this particular scenario, if a user browses to the root path of the application, the response will come up in the form of a string "Hello World".

But, it's just not about strings in response. You can get a json object wrapped up in a response and displayed on the browser just as shown in the next piece of code.
  1. res.send({  
  2. message: "Hello Books"  
  3. });  
  4. })  
  5. app.listen(3000, () => {  
  6.     console.log("The web server is up and running!");  
  7. });  
The last piece of code is used to start the server on the mentioned port number(first argument) i.e. 3000 and have it seated there to handle any incoming requests. Since spinning up a server can take some time owing to other CPU processes, it's generally better to include a callback function as a second argument to the listen method that can notify the user as and when the server gets started.

With all of that code written, simply run the server.js file (by typing "node server.js") and witness the magic that the Express framework casts upon you.

PS - Look out for the notification message that comes up on the console after the server gets started and launched.


Now what about serving a static html file that is saved in your application path and would ultimately be present on the application path in the web server.

Create an HTML file inside a folder named "public" located in application folder and name it as Hello.html.
  1. <html>  
  3. <head>  
  4.     <title>The Hello HTML File</title>  
  5. </head>  
  7. <body>  
  8.     <p>This is the body of the HTML file</p>  
  9. </body>  
  11. </html>  
Paste the following markup in there.

Now to render this static file, we would need to let the Express framework know how to handle the requests for static files.
  1. app.use(express.static(_dirname + "/public"));  
Add this piece of code to tell Express that for treating requests for any static files, it should look for that static file inside the public folder and serve it to the browser. The use method here denotes an Express middleware function which is a topic for a separate day. The "__dirname" is a reserved keyword that denotes the application root path.

For now, just paste in the code in your server.js file before starting the server and run your code again.

And there we have our HTML file.

So, in this blog, I mainly covered the basic utitlity functions that Express provides us with and are majorly used across mostweb based node.js apps.

Ok then, that's it for now and watch out for my next write up focussed on Express Middleware 

Until then, stay safe and Happy Coding!