-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
36 lines (34 loc) · 1014 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
const fs = require('fs')
const path = require('path')
const http = require('http')
const hostname = 'localhost'
const port = 3000
const server = http.createServer((req, res) => {
console.log('requisição:', req.method, req.url)
console.log('cabeçalhos:', req.headers)
if (req.method != 'GET') {
res.statusCode = 405
res.setHeader('Content-Type', 'text/html')
res.setHeader('Allow', 'GET')
return res.end(`<h1>Error 405: ${req.method} is not supported</h1>`)
}
let targetResource
if (req.url == '/')
targetResource = '/index.html'
else
targetResource = req.url
const filePath = path.resolve('./public' + targetResource)
fs.exists(filePath, (exists) => {
if (!exists) {
res.statusCode = 404
res.setHeader('Content-Type', 'text/html');
return res.end(`<h1>Error 404: ${req.url} not found</h1>`)
}
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
fs.createReadStream(filePath).pipe(res)
})
})
server.listen(port, hostname, () => {
console.log(`servidor escutando em http://${hostname}:${port}/`)
})