Skip to content

Instantly share code, notes, and snippets.

@DyadicGit
Last active July 2, 2020 08:25
Show Gist options
  • Save DyadicGit/49be366060205375f4fc28346980e526 to your computer and use it in GitHub Desktop.
Save DyadicGit/49be366060205375f4fc28346980e526 to your computer and use it in GitHub Desktop.
basic node.js server with GET endpoints & without express
const https = require('https');
callback = returnFn => response => {
let str = '';
response.on('data', chunk => {
str += chunk;
});
response.on('end', () => {
returnFn(str);
});
}
const backup = (value) => console.log(value)
const getHtmlDoc = (url, returnFn = backup) => https.request(url, callback(returnFn)).end();
const http = require('http');
http.createServer((req, res) => {
const sendJson = (data) => {
res.writeHead(200, {'Content-Type': 'application/json'});
res.write(JSON.stringify(data) );
res.end();
}
const sendHtml = (data) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
switch (req.url) {
case '/wiki':
getHtmlDoc('https://www.wikipedia.org/', sendHtml)
break
case '/json-data':
sendJson({ data: [1,2,3] })
break
default:
sendHtml('<h1>Hello World!</h1>')
}
}).listen(3000, () => {
console.log("server start at port http://localhost:3000");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment