status-codes.js 637 Bytes
const fs = require('fs')
const http = require('http')
const path = require('path')

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    // Redirect `/` to `/index.html`
    res.statusCode = 301
    res.setHeader('Location', '/index.html')
    res.end() // don't send any response
    return
  }

  // By default, `res.statusCode` is 200 OK
  const readStream = fs.createReadStream(path.join('files', req.url))
  readStream.on('error', _ => {
    // Indicate the file didn't exist with a 404
    res.statusCode = 404
    res.write('File not found')
    res.end()
  })
  readStream.pipe(res)
})
server.listen(80)