Created
November 24, 2019 20:43
-
-
Save kraftwerk28/9077f8bf172e7a8e09736e984085d7ac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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