Introduction: How to Make a Server Using Node.js
Hi,I'm currently studying about web development and here is a step by step guide on how i do it. I'am no expert and some mistakes are unintentionally done. Thus, any comments/and suggestions are welcome.
I'am currently using windows 10 and here is the list of Software i used and installation guides i followed:
- Visual Studio Code(https://code.visualstudio.com/download)
- Nodejs(https://www.guru99.com/download-install-node-js.ht...
Visual studio code is the IDE i used to code in node js to make a server.
Step 1: Make a Package.json File
A package.json describes and helps in deploying nodejs app and its dependencies. when npm install is used in the terminal, the npm will download all dependencies in the packgae json file. The dependencies consist of modules(libraries) that is necessary to use this app. Thus, On visual studio code,
- go to file and open a folder. If there is none, create a new folder for your project files
- go to terminal and see picture no 2.
- In the terminal type "npm init" to create a package.json file.This will prompt you questions to form a package file with a format as shown in pic 3.
- To add a module, in the terminal type npm install [--save-prod] for necessary modules your app uses
- To add a module you as the developer use typenpm install --save-dev
Step 2: Create Your App
First, install nodemon as a dev dependecies by typing "npm install nodemon --save-dev" on the terminal. Then add a new file on the folder you just made. In my case, i made it as "CreateDB.js". Type/copy this code on VSCODE and go to the terminal and type "nodemon <NameOfYourJSFile> to run the program. Go to you browser and open "http://localhost:8000/" to see a local server that says "hello world :D, finished responding".
//a built in module of node js to make the Node.js act as an HTTP server const http = require('http');
/*Creates an HTTP server that accepts request (req) and respond(res). Once the server is open it is considered as a "request". This function then responds to that request with hello world. */ http.createServer(function(req,res){ res.writeHead(200,{'Content-type':'text/plain'}); //describes the file type of the reponse res.write("hello world! :D \n"); //Send the text "Hello world :D" to the server."\n" is to create new line res.end("finished responding"); //is mandatory for each response and tells the program that that all of the response has been sent }).listen(8000); //delegate this server to listen to PortNumber "8000". thus it can be open using http://localhost:PortNumber