Node Js Hello World

Posted on  by admin

Before diving in, you should know the basic concepts of JavaScript. Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside a web browser.

Configure your first Node.js app using Developer Portal

Node is an asynchronous event driven JavaScript runtime built upon Chrome’s V8 JavaScript engine. It’s designed to build scalable network applications.

Actually, JavaScript was made for just the front-end but now it can be used in server side with the help of Node.js.

Step 4:

Asynchronous means, handling events without interrupting the main thread because JavaScript is single threaded, meaning there is only one thread of execution.

  • Let’s get going. You should have Node.js installed in your PC to use it(Quite obvious).
  • Goto : https://nodejs.org/en/Download and install Node.js according to your OS.
  • It’s super easy to install. Create a folder somewhere on your PC and open terminal or cmd or whatever and set the directory to that folder.(I am using cmd in Windows10).

cd => change directory.mkdir => make directory. Now we need to initialize our project. Run the following to do that:. npm => Node Package Manager. This is what you might see next:. Fill it accordingly or just go with default.

This is mine: 👐. Now if you check your current directory, you can see a package.json file with all the above details.(you can change the values in it).

Create a file named index.js and open it and fill it like this 👇.
Now in cmd run :.
This will start a test server at localhost , http://localhost:3000/, goto this url to view the page.
I will now explain what’s in the code: 👇.
✅ const http = require(‘http’); => this will import http module in Node.
✅ const hostname = ‘localhost’; const port = 3000; This above is used to initialize hostname to localhost and port to 3000.
✅ console.log(req.headers); =>this is used to show the geeky details on your terminal when the server starts.
✅ http.createServer =>this turns your computer into an HTTP server.We pass a function as argument in it with arguments res and req.In the code you see a JavaScript arrow function.
✅ res.end() => will end the response process.
This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.
It is used to quickly end the response without any data.You can pass a string argument to add as the response body as we have did that here.
✅ res.statusCode = 200 => This is used to sent back HTTP status code.
200 is code for OK. ✅ server.listen(port, hostname); => Create a server that listens on port 3000 of your computer.

✔️ You can also use npm start to start the server. For that you need to add an additional line at script in package.json.

Now you can start server using npm start. ✔️ Hot Reload.You need to restart the server every time when you change anything in the code and it’s quite annoying.