Tuesday, April 20, 2021

How to create a HTTP server, listener and response with NodeJS at runtime?

Pre-requisute: Install nodejs, visual studio code and the http modul

Descrption: The use of createServer from http module - will help create an object that servers as a webserver running on localhost:8080

const {createServer} =require('http');
cons server=createServer((request,response))=>{
    response.writeHead(200,{'Content-Type':'application/json'});
    response.write(JSON.stringify({a:1,b:2,c:3}));
    return response.end();
});

server.listen(8080);

What does this mean?

This means, you can technically launch a webserver on the fly and create a response work temporarily and shut it down. 

I am assuming its a good strategy to not have a webserver always running, but that question is for another day.

Cheers

Credits : https://www.youtube.com/watch?v=TrofE5tDRag

No comments:

Post a Comment

Please add value. Sharing is caring