This article shows how you can use Express Framework for creating Web based Application in Node.js.
Express is a free and open-source Node.js web application framework.
Create a Hello World application using Express Framework
Here’s a step-by-step guide:
1) Go to the folder where you want to create your new Node.js application/module.
2) In my case, my working Node.js directory is /var/www/html/test/nodejs
mukesh@chapagain:~$ cd /var/www/html/test/nodejs
mukesh@chapagain:/var/www/html/test/nodejs$
3) Create a new folder for your module. I will create a new folder named myapp. This is the name of my module.
mukesh@chapagain:/var/www/html/test/nodejs$ mkdir myapp
4) Go inside your module directory.
mukesh@chapagain:/var/www/html/test/nodejs$ cd myapp
5) Run npm init command which will create package.json file for your module. It will ask for certain questions like your module’s name, description, version, author, etc.
mukesh@chapagain:/var/www/html/test/nodejs$ npm init
6) Install Express Framework with the following command:
mukesh@chapagain:/var/www/html/test/nodejs$ npm install express -save
Using -save option in the install command will update package.json file to add express module dependency for our module.
7) Create a new file named app.js.
var express = require('express');
var app = express();
app.get('/', function(request, response){
response.send('Hello World');
});
app.listen(3000, function(){
console.log('Server running at port 3000: http://127.0.0.1:3000');
});
The code above, loads the express module library. The express app starts the server and listens to port 3000. For the request of root URL (‘/’), the app responds with Hello World text.
8) Run node app.js in your terminal:
mukesh@chapagain:/var/www/html/test/nodejs/myapp$ node app.js
Server running at port 3000: http://127.0.0.1:3000
9) Now, open your browser and browse http://127.0.0.1:3000 text displayed in your browser.. You should be able to seeHello World
That’s all. You have created your first application using Node.js and Express Framework.
Hope this helps. Thanks.