Express JS Hello World example


Prerequisites: Make sure you installed Node.js already. If not try installing, before moving to below steps.

  • First create a directory named called myapp.
  • Open command prompt using myapp folder and run npm init. Enter some details which are required to be selected and entered like name of the application, version, description, entry point(accept entry point as index.js) and licence(Just press enter for licence will be automatically picked and just we need to confirm that's it).

npm init

After that just check package.json file, which got created in myapp folder.

package.json
	  
{
  "name": "myapp",
  "version": "1.0.0",
  "description": "My First Express Js Application",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "express",
    "js"
  ],
  "author": "soha",
  "license": "ISC"
}	 

Now install Express in the app directory and save it in the dependencies list. For example:

	 	 
npm install express --save

To install Express temporarily and not add it to the dependencies list, omit the --save option:

	 	 
npm install express

Create file called index.js in myapp folder with below code.

index.js
	 	 
var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(4000, function () {
  console.log('Example app listening on port 4000!');
})

Project Structure

Express js Project structure

Once we starts a server and listens on port 4000 for connections. The app responds with "Hello World!" for requests to the root URL (/) or route.

Run the app with the following command:

	 	 
node app.js

Then, load http://localhost:4000/ in a browser to see the output.

Express js hello world example

.