create a http server on a specific port and host in javascript

To create an HTTP server on a specific Port and Host in JavaScript, you can use the built-in http module in Node.js. Here is an example code snippet:

index.tsx
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
340 chars
15 lines

In this code snippet, we first import the http module and declare the hostname and port that we want to run our server on. We then create a server using the http.createServer() method, which takes a callback function that will be executed whenever a request hits our server. In this example, we simply set the HTTP status code to 200, set the Content-Type header to text/plain, and send a "Hello World" message as the response.

Finally, we use the server.listen() method to start the server and listen on the specified port and hostname. The callback function provided to server.listen() is executed when the server starts and logs a message to the console to confirm that the server is running.

gistlibby LogSnag