Skip to content

Node Web Server

Creating a Web Server

Developer can create a web server with Node built-in http module, which allows Node to transfer data over the Hyper Text Transfer Protocol (HTTP). To include the HTTP module, use the require() method and specify hostname and port. Use the createServer() method to create an HTTP server.

The function passed into the http.createServer() method, will be executed when someone tries to access specified hostname and port. A Request object req encapsulates the HTTP request sent by the user, which is the first argument. The HTTP response that is returned to the user is generated by interacting with the Response object res which is the second argument.

server.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'})
  res.write('Hello World!')
  res.end()
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})

Web server can be started with node:

1
2
node server.js
Server running at http://127.0.0.1:3000/

Try it from your browser and you should see 'Hello World!' text in your browser.

Status code 200 tells the clients browser that the request succeeded. Check out other HTTP response status codes from Mozilla Developer Network HTTP response status codes.

Returning a HTML content

Server can be easily modified to returning a HTML just changing the content type to text/html.

1
2
3
res.writeHead(200, {'Content-Type': 'text/html'})
res.write('<h1>Hello World!</h1>')
res.end()

Try it from your browser and you should see 'Hello World!' header in your browser.

A HTML file can be read from the filesystem with Node's fs module and then send it to the client in the response.

server2.js
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
const http = require('http')
const { readFileSync } = require('fs')
const hostname = '127.0.0.1'
const port = 3000

const index = readFileSync('./index.html')

const server = http.createServer((req, res) => {
  res.writeHead(200, { 'content-type': 'text/html' })
  res.write(index)
  res.end()
})

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})

We will work more web servers with Express.

Read more

Goals of this topic

Understand

  • Node Web Server