First, we need to create a project folder that will house the files for our sample project
Then we initialize our NodeJS project using npm with the -y
flag to accept the default values.
mkdir simple-server && cd simple-server
npm init -y
In order to set up a minimal server we would need to install our dependencies.
npm install --save express
create our entry index.js
file and open in your editor of choice.
touch index.js
Type in the following in the index.js file
const express = require('express');const app = express();
app.use((req, res, next) => { return res.json({ message: 'Simple express server' });});
app.listen(3000, () => console.log('server started on port 3000 π'));
Run the index.js
file to get the server running
node index.js
Visit http://localhost:3000/app and you should see something similar to the image below to confirm that our initial setup is working well.
Setting up the static file server
Now that we have a working express server, we need to set it up to serve static files like HTML, CSS, jpg etc from a local directory.
Add the following to our index.js
file between the calls to app.use...
and app.listen...
.
//...
app.use((req, res, next) => {
return res.json({
message: 'Simple express server'
});
});
app.use('/', express.static('./public'));
app.listen(3000, () => console.log('server started on port 3000 π'));
What this does is serve the content in the public
directory when the index route is hit.
The only thing that is left is to move the HTML files into the public folder. We currently donβt have that folder so we would need to create it and add the static files in it.
mkdir public
touch public/index.html public/main.css
Open your text editor, then copy and paste the following content to the index.html
and main.css
files respectively.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<h1>Simple static file server with Node/Express</h1>
</body>
</html>
h1 {
font-size: 40px;
text-align: center;
}
Visit http://localhost:3000 and you should see the HTML and CSS content being served from your express server.