Skip to content

Instantly share code, notes, and snippets.

@rajiff
Created April 17, 2018 04:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajiff/0a481d24a93b824014c5bdaeb1785bc3 to your computer and use it in GitHub Desktop.
Save rajiff/0a481d24a93b824014c5bdaeb1785bc3 to your computer and use it in GitHub Desktop.
NodeJS vanilla handling requests
const http = require('http');
const url = require('url');
// const querystring = require('querystring');
let server = http.createServer(function(req, res) {
let isMatched = false;
console.log("Got a new Request ", req.method, " => ", req.url);
// Query string parameter
let urlParts = url.parse(req.url, true);
console.log('Request parsed path ', urlParts.pathname);
console.log('Request parsed query parameters ', urlParts.query);
if(req.method === 'GET' && req.url === '/foo') return res.end('bar');
if(req.method === 'PATCH' && req.url === '/foo') return res.end(`PATCH bar`);
if(req.method === 'POST' && req.url === '/foo') {
isMatched = true;
let data = [];
req.on('data', (chunk) => data.push(chunk));
req.on('end', (d) => {
console.log('end data ', d);
data = Buffer.concat(data).toString();
return res.end(`POST bar ${data}`);
})
}
if(req.method === 'GET' && req.url === '/bar') return res.end('foo');
if(req.method === 'GET' && req.url === '/suresh') return res.end('ramesh');
if(req.method === 'GET' && req.url === '/ramesh') return res.end('suresh');
if(req.method === 'GET' && req.url === '/hello') return res.end('hello world');
if(!isMatched){
res.writeHead(404);
res.end('Resource not found')
}
});
server.on('connection', (socket)=> console.log(' ** CONNECTION ** ', socket.address()));
server.on('request', ()=> console.log(' ** REQUESTED ** '));
// server.on('close', ()=> console.log(' ** CLOSED ** '));
server.on('error', (e) => {
if (e.code === 'EADDRINUSE') {
console.log('Address in use, please check if another process is using the port and retry...');
} else if (e.code === 'EACCES') {
console.log('There seems to be a access permission or privilege issue with user account used to run the service, please check and try again..!');
}
});
server.on('listening', () => { console.log('Server is listening on ', server.address())});
server.listen(process.env.PORT || 9090);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment