Configure your first Node.js app using Developer Portal
- 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.
✅ 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.