Skip to content

Instantly share code, notes, and snippets.

@syuhendar729
Created July 5, 2021 14:20
Show Gist options
  • Save syuhendar729/ace31fb75d8b010c7217d81daba12f90 to your computer and use it in GitHub Desktop.
Save syuhendar729/ace31fb75d8b010c7217d81daba12f90 to your computer and use it in GitHub Desktop.
File nodejs web server
/* === Nodejs web server ===
*
* dgn module `http`
* http.createServer(callback(require, respon))
* .listen(port, hostname, callback())
*
* */
const http = require('http')
const fs = require('fs')
const port = 3000
/* --- Buat server dengan createServer() --- */
const server = http.createServer( (req, res) => {
/* -- ubah type content menjadi html -- */
res.writeHead(200, {
'Content-Type': 'text/html' // => default plain text
})
/* -- buat routing dari request url -- */
const url = req.url
if (url === '/contact') {
res.write('Ini halaman contact')
} else if (url === '/about') {
res.write('Ini halaman about')
} else {
fs.readFile('./index.html', 'utf8', (err, data) => {
if (err) {
res.writeHead(404)
res.write(`Error : ${err}`)
} else {
res.write(data)
console.log(data)
}
})
}
/* -- akhiri respond -- */
res.end()
} )
/* -- Jalankan server dgn listen() -- */
server.listen(port, () => {
console.log(`Server is listening on port ${port} ... `)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment