Wednesday, September 18, 2019

NodeJS - HelloWorld with ExpressJS

In this tutorial, you are going to learn how to create an express application using Express Generator and create a hello world page by creating a new route file in nodejs.

This tutorial tested on Nodejs v10.16.2 and Expressjs v4.16.1.

1. Install Express Generator. Create the application skeleton using application generator tool. Go to the project folder and type “npm install -g express-generator”

2. Create Express Project using EJS view engine. By default, Express is using PUG view engine. For this example, we are using EJS. Use this command “express --view="ejs" [folder name]” to create the express project. Example: “C:\Users\simon.siah\workspace>express --view="ejs" nodejs-expressjs-starter”.

















3. Install dependencies. Type below command to install dependencies. It will read the package.json and install the stuff.





4. Start the server Type below command to start the server.




5. Open a browser and type http://localhost:3000/.











6. Route files. - The route files store in folder routes. - This section in app.js define the http routes. - Example: /, is using routes/index.js and /users us using routes/user.js.

7. View files - The view files store in folder views.

8. Create a Hello World Page.
  • Copy the routes/index.js and paste into folder routes, rename the files to helloworld.js. 
  • Change the content below:
  • Create helloworld.ejs in views folder: 
  • Update app.js to include helloworld route:
     
  • Start the server and enter URL -> http://localhost:3000/helloworld 
Changing the EJS templates does not require a server restart, but whenever you change a JS file, such as app.js or the route files, you'll need to restart the see the changes.

I am using sublimetext as IDE to update the sources. It is free, and you can download here: http://www.sublimetext.com/ 

Here are some useful references: 

Node.js, Express.js, MongoDb Tutorial:  

Node.js: 

Express.js: 

No comments:

Post a Comment