Get started with Expressjs

This article will demonstrate how to get started with Expressjs, an easy to use Node.js web application framework.

To start with, you’ll need to ensure you have downloaded Node.js which comes with the npm (Node Package Manager)

If you’ve installed Node correctly, you should be able to see the current version installed by running the following in your terminal:

$ node -v
v4.6.0

The article will be using the Express application generator, which can be installed via the npm command.

$ npm install express-generator -g

Now you’ll be able to set up an Expressjs application. Head to a directory on your computer that will contain your project and run the below.

$ express myapp

You should now have Expressjs files and folders set up in the “myapp” directory.

Open up the app.js file and add the following code near the bottom of the file.

app.listen(3000,function(){
   console.log('Express server listening');
})

When the application starts running, it’ll listen on port 3000 for connections.

To run the application, simply type in the terminal:

$ node app.js

If you haven’t installed any node modules, you’ll more than likely comes across errors when your application looks for modules that currently don’t exist i.e. Cannot find module ‘express’.

To rectify these errors, you can install the modules via npm within your current working directory.

$ npm install express
$ npm install serve-favicon
$ npm install morgan
$ npm install cookie-parser
$ npm install body-parser

If you then re-run the app.js, you should see the following.

$ node app.js
Express server listening

You can then head to your browser and type in localhost:3000 in the address bar to view your application.

You may get presented with the following.

Get started with Expressjs

To resolve this error, simply install the jade module.

$ npm install jade

Re-run your application by executing the ‘node app.js’ command, head to the browser and you should see the following.

Get started with Expressjs

Congratulations! You are now running your own node server using the Expressjs framework.