In this tutorial, I will show you how to start an HTTP server using a very popular NodeJS module, the http module.
First, I will create a new NodeJS project as an example:
In the above steps to create a NodeJS project, there is a step that defines the main entry point of the application using the index.js file, so I will create this new file.
We will use the require() function to declare using the http module:
1 |
const http = require("http"); |
Next, we will initialize the Server object using the http module’s createServer() method:
1 2 3 4 5 |
const httpServer = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); }); |
As you can see, I have initialized the Server object with the information that if the user requests to this Server, the text “Hello World” will be returned.
Now, we will use the listen() method of the Server object to start this server:
1 |
httpServer.listen(8080, () => console.log('Server running on port 8080')); |
At this point, we have finished starting an HTTP server using NodeJS’s http module.
The output when running this application using the command “node index.js” is as follows:
Go to the application’s address, you will see the following results: