Your first HTTP server
Now that we know how to use the EventEmitter class, let’s build a simple HTTP server. We will use the http core library to create the server and the EventEmitter class to handle the requests. In Chapter 9, we will explore in more detail how to build HTTP servers and clients, but for now, let’s focus on building our first HTTP server.
Let’s create a file called server.mjs and add the following code:
import { createServer } from 'node:http';
const port = 3000;
const server = createServer();
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>This is my first HTTP server in Node.js. Yay</h1>!');
});
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}/`);
}); In this example, we created an instance of the http.Server class and registered an event...