Setting up express js server in ubuntu

Today we are going to set up simple express js server in ubuntu. For this tutorial we are going to use express generator since it makes initial set up process easier.
The prerequisite for this tutorial is that you have nodejs preinstalled.
The steps are as followed:
1)It is better to install express-generator globally since you are going to use it many times in the future.The command is:
npm install -g express-generator

2)Run the following command to create default directories:
express sample

3)Change directory and install dependencies as:
cd sample && npm install

4)Run the app as follows:
PORT=4000 npm start
If you open localhost:4000 on your browser you will see following page:


5)Open up your favourite text editor like sublime or atom and add project folder as sample folder.
If you look at app.js the structure can be explained as follows:

This creates a bunch of JavaScript variables and ties them to certain packages, dependencies and routes.
var app = express()
instantiates app variable with express module.
In the further steps we are going to use this variable to do all kinds of tasks.

app.use('/', routes);
app.use('/users', users);

This creates basic routes which get served on localhost port i.e. / route serves all gets requests on port 4000 while /users serves all get requests on localhost:4000/users/ route.

The server is instantiated in /bin/www file where
var server = http.createServer(app);
creates the http server to serve files and requests.

6)Lets create simple hello world in express:
Go to routes/index.js file.
Here you will existing route of / which prints expess
Add another route below it as:

// HELLO WORLD routes
router.get('/helloworld', function(req, res) {
res.render('helloworld', { title: 'Hello, World!',text: 'I am a programmer' });

7)Create helloworld.jade in views folder and insert following code:

8)Now kill npm start and restart it again and point your browser to localhost:4000/helloworld/
It should give you something like this:


Thats it for todays tutorial.In the next tutorial we are going to set up mongodb on ubuntu and connect it with nodejs which is posted here. Till then enjoy your life as developer and happy coding.

Share post-
About Saurabh Mhatre 70 Articles
Currently working in web and hybrid application development