Skip to content

Instantly share code, notes, and snippets.

@kraftwerk28
Created November 24, 2019 20:43
Show Gist options
  • Save kraftwerk28/9077f8bf172e7a8e09736e984085d7ac to your computer and use it in GitHub Desktop.
Save kraftwerk28/9077f8bf172e7a8e09736e984085d7ac to your computer and use it in GitHub Desktop.
'use strict'
const { resolve, extname } = require('path')
const http = require('http')
const fs = require('fs')
const PORT = process.env.PORT || 8080
const PUBLIC_PATH = 'public/' // place it directory, where you execute node
const MIME_TYPES = {
'css': 'text/css',
'html': 'text/html'
}
http.createServer((req, res) => {
const url = req.url === '/' ? 'index.html' : req.url.slice(1)
const path = resolve(PUBLIC_PATH, url) // style.css
console.log(path)
const ext = extname(path).slice(1) // .css
const mimeType = MIME_TYPES[ext]
? MIME_TYPES[ext]
: 'text/plain'
fs.readFile(path, (err, data) => {
if (err) {
res.writeHead(400, { 'content-type': 'text/plain' }).end('No such file')
} else {
res.writeHead(200, { 'content-type': mimeType }).end(data)
}
})
}).listen(PORT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment