Create Server NodeJS
Thu Jan 25 2024 17:21:36 GMT+0000 (Coordinated Universal Time)
Saved by
@Pirizok
const http = require('http')
const fs = require('fs')
const path = require('path')
http.createServer((req, res) => {
if(req.url === '/'){
sendRes('index.html', 'text/html', res)
}
else if(/\uploads\/[^\/]+$/.test(req.url) && req.method === 'POST'){
}
else{
sendRes(req.url, getContentType(req.url), res)
}
}).listen(5000)
function getContentType (url){
switch(path.extname(url)){
case '.html':
return 'text/html'
case '.css':
return 'text/css'
case '.js':
return 'text/javascript'
case 'json':
return 'application.json'
default:
return "application/octate-stream"
}
}
function sendRes(url, contentType, res){
let file = path.join(__dirname+'/static/', url)
fs.readFile(file, (err, data) => {
if(err){
res.writeHead(404)
res.write('Error')
res.end()
console.log('error 404')
}
else{
res.writeHead(200, {'Content-Type': contentType})
res.write(data)
res.end()
}
})
}
content_copyCOPY
Comments