Seleccionar página

Node.js Express Framework tutorial

What is Node.js?

Node.js is an open-source and event-driven JavaScript run-time environment. Node.js allows us to create web servers with a non-blocking event-driven architecture using JavaScript.

Event-driven architecture

The most important difference between Node.js and other technologies or programming languages that also allow creating web servers (i.e. PHP or Java) is the use of an Event Loop instead of creating a thread for each client. The way that traditional web servers face the problem of having large amount of clients making requests to the server is creating a new thread for each request, which means a big inefficiency in terms of memory. Node.js instead relies on a single-thread running an Event Loop which manages all the asynchronous operations and eliminates the waiting.

“When a Node application needs to perform a blocking operation (I/O operations, heavy computation, etc) it sends an asynchronous task to the event loop, along with a callback function, and then continues to execute the rest of its program. The event loop keeps track of the asynchronous operation, and executes the given callback when it completes, returning it’s results to the application. This allows you to manage a large number of operations, such as client connections or computations, letting the event loop efficiently managing the thread pool and optimize task execution” – Udemy blog, CONSTANTINE AARON COIS

In summary, Node.js is the solution for developing web servers avoiding threading and using callbacks to notify the completion of tasks.

Node.js Hello World

 

What is Express?

Express is an open-source and minimalist web application framework for Node.js. It provides a set of web application features and tools for HTTP servers. One of the most important features of Express are:

  • Robust routing
  • Focus on high performance
  • Super-high test coverage
  • HTTP helpers (redirection, caching, etc)
  • View system supporting 14+ template engines

Installing Express

The easiest way to install Express is using the Node Package manager by executing the following line:

$ npm install express --save

Congratulations! You have now express installed and ready to use.

Express Hello World

 

Express application generator

The easiest way to use Express v4 is using the express-generator package, which makes it possible to create an application skeleton in a few steps:

  1. Install the package:
     $ npm install -g express-generator@4
  2. Create your app:
     $ express /tmp/foo && cd /tmp/foo
  3. Install dependencies:
     $ npm install
  4. Start the server:
     $ npm start

Well done! You can now access your application opening http://localhost:3000/ in your browser.

Note: This is the resulting files and folders structure:

 .
 ├── app.js
 ├── bin
 │ └── www
 ├── package.json
 ├── public
 │ ├── images
 │ ├── javascripts
 │ └── stylesheets
 │ └── style.css
 ├── routes
 │ ├── index.js
 │ └── users.js
 └── views
 ├── error.pug
 ├── index.pug
 └── layout.pug

Routing

Implementing Express routing functionality is as easy as defining a handler (JavaScript function) for desired path and method. Look at the example below:

//Load the module and creates the Express application
var express = require('express')
var app = express()

//Respond to GET request on the root route (/)
app.get('/', function (req, res) {
res.send('GET request on /')
})

//Respond to POST request on the root route (/), the application’s home page:
app.post('/book', function (req, res) {
res.send('POST request on /book')
})

//Respond to a PUT request to the /user route:
app.put('/book', function (req, res) {
res.send('PUT request on /book')
})

//Respond to a DELETE request to the /user route:
app.delete('/book', function (req, res) {
res.send('DELETE request on /book')
})

app.listen(3000)

Route parameters

You can easily define route parameters directly in the route path:

app.get('/book/:bookId/chapter/:chapterId', function (req, res) {
var bookId = req.params.bookId
var chapterId = req.params.chapterId
})

As you can see in the example above the request object contains the parameter values:

Route path: /book/:bookId/chapter/:chapterId
Request URL: http://localhost:3000/book/3426/chapters/6
req.params: {"bookId": "3426", "chapterId": "6"}

Middleware functions

The app.all() special function allows us to execute some code for all the HTTP request methods on a certain route:

app.all('/book, function (req, res) {
myFunction()
next() // pass control to the next handler
})

Chainable route handlers

There is also the possibility of creating chained route handlers using app.route():

app.route('/book')
.get(function (req, res) {
res.send('GET request on /book')
})
.post(function (req, res) {
res.send('POST request on /book')
})
.put(function (req, res) {
res.send('PUT request on /book')
})

Serving static files

Serving static files in Express is as simple as calling the express.static middleware function:

app.use(express.static('public'))
app.use(express.static('files'))

Even though the previous code works, it’s typical to find the static files served using the absolute directory:

app.use('/static', express.static(path.join(__dirname, 'public')))

Template engines with Express

Express works with multiple template engines such as Mustache, React, Pug (formerly Jade) or Blade (check the whole list here)

First of all you need to install the desired template engine (normally via NPM package manager) and the set the template engine using the following command:

app.set('view engine', 'react')

After setting the template engine, you must specify the views directory:

app.set('views', ./views)

Finally you can use the render() function to render the views, passing the view name and the values object as parameters:

app.get('/', function (req, res) {
res.render('index', { title: 'Hello', message: 'World!' })
})

Handle 404 responses

As you surely already know, 404 is the response code that indicates that the server couldn’t find what was requested. For handling this error code in Express you have to use a middleware function below all other functions:

app.use(function (req, res, next) {
res.status(404).send("We can’t find it!")
})

Error handling

Error handling is very similar to 404 error code handling. The only difference is that you have 4 arguments

app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})

You can find more information about error handling in Express at http://expressjs.com/en/guide/error-handling.html

What’s next?

This Node.js and Express tutorial has explained you how to develop a web server using JavaScript. You can now continue practicing and developing your first Rest API. If you want you can also add some front-end code to your app following some of the previous tutorials like Creating a React app in 5 minutes or the Introduction to React.

Happy coding!

Sources