Skip to content

Express.js - a true server

Now that we've seen how Node.js and its modules work, let's build a simple web server using the express package.

Installing express

To install express, we need to have a package.json file in our folder (run npm init if you don't have one) and then install the package:

1
npm install --save express

Building a simple server

Open up a new file and type the following code:

1
2
3
4
5
6
7
8
const express = require('express')
const server = express() // This creates a new express server

server.get('/', function (request, response) {
  response.send('Hello!')
})

server.listen(3000)

You can now run this file as such:

1
node index.js

Open up your browser to http://localhost:3000/ and voila! Your new server is up and running!

Serving static files

Static files - HTML, CSS or JS files. In other words, anything that is not a JSON response generated by the server

We've made our first server, but it isn't very useful just yet. Let's set it up so that it can deliver us a simple HTML page. Assuming that your files are located in the website/ folder, you can tell Express to serve everything in there like this:

1
2
3
4
5
6
const express = require('express')
const server = express()

server.use(express.static('website'))

server.listen(3000)

Run the script and see how it works!

Reading and writing from files

We can read and write files by using the fs(filesystem) module. We don't need to install this, as this is already included in Node.js:

1
2
3
4
5
6
7
const fs = require('fs')

fs.writeFile('./test.txt', 'hello')

fs.readFile('./test.txt', function (err, data) {
  console.log(data)
})