create a http server on a specific port in javascript

Here's a simple example of how to create an HTTP server on a specific port in Node.js:

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

const PORT = 8080;

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

server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
287 chars
14 lines

In this example, we first import the http module, which is included with Node.js. We then specify the port number we want to use for our server, in this case 8080.

Next, we create a new HTTP server using the http.createServer() method. This method takes a callback function that will be called every time a request is made to the server. In our callback function, we set the statusCode of the response to 200, indicating a successful request, and set the Content-Type header to text/plain.

Finally, we start the server listening on the specified port using the server.listen() method. We also log a message to the console indicating that the server is running on the specified port.

If you run this code in your terminal using the command node server.js (assuming you save the file as server.js), you should see the message "Server running on port 8080". You can then make a request to http://localhost:8080 in your browser to see the "Hello, World!" response.

gistlibby LogSnag