Skip to content

Instantly share code, notes, and snippets.

@tzwel
Last active February 2, 2023 06:48
Show Gist options
  • Save tzwel/f90ca6bff3288d25a3dce5b2db586bc4 to your computer and use it in GitHub Desktop.
Save tzwel/f90ca6bff3288d25a3dce5b2db586bc4 to your computer and use it in GitHub Desktop.
The simplest Node.js server
const http = require('http');
let appOptions = {
'localHostUrl': 'http://localhost:'
//errorHandler
}
let routes = {}
const app = {
route: function(route, action) {
if (!routes[route]) {
if (!route.startsWith('/')) {
route = "/" + route
}
routes[route] = {route: route, action: action}
}
},
option: function(optionName, optionValue) {
appOptions[optionName] = optionValue
},
serve: function(port) {
http.createServer(function (req, res) {
const route = routeParser(req.url)
if (routes[req.url]) {
route.action(req, res)
} else {
if (routes['/404']) {
routeParser('/404').action(req, res)
} else {
errorHandler(req, res)
}
}
}).listen(port)
console.log(`Website listening on port ${port} (${appOptions.localHostUrl + port})`);
}
}
function routeParser(route) {
return routes[route]
}
function errorHandler(req, res) {
if (appOptions['errorHandler']) {
appOptions['errorHandler'](req, res)
} else {
res.writeHead(502, { 'Content-Type': 'html' });
res.write('An error has occured.')
res.end()
}
}
exports.app = app;
@tzwel
Copy link
Author

tzwel commented Jan 31, 2023

const {app} = require('./nakadashi.js')

app.route('/', (req, res) => {
    const random = Math.floor(Math.random() * 10)
    res.writeHead(200, { 'Content-Type': 'text' })
    res.write(`Hi! Your server is set up correctly. Here's a random number for you: ${random}`)
    res.end()
})

app.route('404', (req, res) => {
    res.writeHead(200, { 'Content-Type': 'text' })
    res.write('Page not found.')
    res.end()
})

app.serve(3000)

Nakadashi Hello World

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment