Previously we have seen the steps to install node.js on macOS Sierra, you can check the installation guide here. Now, it’s time for our first node.js application. Yet again another “Hello World” application using Node.JS.
Before starting though it would be great to check out the important components of node.js:
- Import required modules: We use the require directive to load Node.js modules.
- Create server − A server which will listen to client’s requests similar to Apache HTTP Server.
- Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.
Let’s kick start
Create a directory and call it example.
Then create a file inside the directory called main.js
Step 1 – Import Required Module
We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows −
var http = require("http");
Step 2 – Create Server
We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 8081 using the listen method associated with the server instance. Pass it a function with parameters request and response. Write the sample implementation to always return “Hello World”.
The above code is enough to create an HTTP server which listens, i.e., waits for a request over 8081 port on the local machine.
Now execute the main.js to start the server as follows −
$ node main.js
Verify the Output. Server has started.
Server running at http://127.0.0.1:8081/
Congratulations, you have your first HTTP server up and running which is responding to all the HTTP requests at port 8081.
[alert type=white ]
Open http://127.0.0.1:8081/
in any browser and observe the following result.
Happy coding! 🙂 Check out the source code on my github account
[/alert]