In the previous post we only logged something to the console. In this post we’ll take it a little further a make a web page.

Setting up our project

First you can start a new project with npm init. Feel free to copy my package.json file.

{
"name": "hello-world-express",
"main": "server.js"
}

Install Express

Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications.

We can install this by typing npm install express --save in our terminal.

Our package.json file should look something like this now:

{
"name": "hello-world-express",
"main": "server.js",
"dependencies": {
"express": "^4.14.0"
}
}

Make our Web Page

Make a new file named index.html. Feel free to make your own web page, or copy mine.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello World</title>
<style>
body {
text-align: center;
background: #EFEFEF;
padding-top: 50px;
}
</style>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>

Using Express

Now that we’ve finally set up our project, it’s time to start using Express to make our web app.

Make a new filed called server.js and type in the following

var express = require('express');
var app = express();
var path = require('path');

app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});

app.listen(1337);
console.log('You can find your web page at http://localhost:1337');

Now you can start the server by with the terminal command node server.js Navigate to http://localhost:1337 in your web browser to see what you’ve made!

Tip: Use Nodemon

If we start our server with node and make changes to our project, we have to stop our project and start a new one. Luckily there’s a great npm package called Nodemon which makes this process easier for us by restarting our server whenver we make a change in our project.

Installed nodemon with via terminal with npm install -g nodemon Now instead of using node server.js to start our server you can use nodeman server.js.

Go ahead and make some changes to your index.html file to test this out.

Project Code

You can find the code to this project here