Node.js is a Javascript platform that is built on Chrome's V8 Javascript engine and allows you to build powerful applications.
1. Installing Node
You can install node js by visiting this link
2. Setting up Node
After you have downloaded and installed node.js from the above link, it's time to set up the project directory!
- Create an app directory
- Create a file named index.js in that directory
There you go! You have successfully set up a basic node.js project directory!
3. Creating the server
We will be creating a basic HTTP server in our index.js file. For that, we need to first import the http module inside our file. To do that write the following line inside index.js :
const http = require("http);
Next write the following lines of code:
http
.createServer((req, res) => {
res.writeHead(200, { "Content-type": "text/plain" });
res.end("Hello World\n");
})
.listen(3000);
The createServer function called above is used to create a basic HTTP server. We have passed a callback function to it as an argument. The callback function has two parameters: req which represents the request part and res which represents the response part.
Inside the callback function, we write the following lines of code:
-
The first line uses the res.writeHead methods to set the response code and the header object for the response that our server is going to send.
The second line we use the res.end function to send a response and end the request-response cycle. Here we have returned the customary Hello World greeting.
The listen function tells the server to listen for any requests on the port passed as the parameter. Here we pass 3000 as port.
In the last line, we log something to the console so we know the server has started and is working.
After this navigate to your directory and in the terminal type the following command node index.js
After this navigate to http://localhost:3000 and voila! You should see Hello World written in your browser.
To stop the server use Ctrl+c
And just like that, you have created your basic Node.js server! Stay tuned for more articles like this!
Top comments (6)
Nice!
Thanks!
Great! Node-express syntax are almost same
Yes 😁. In express it's even easier to setup!
Kudos!! 🔥👏
Thanks!