NodeJs Beginners guide-How to create server

Christopher Zach
techimania
Published in
2 min readOct 2, 2019

Step-1

First we installed nodejs and checked the version using command node -v/node — version in cmd prompt.

Step-2

Go to command prompt and create a directory in desktop or anywhere as per your convenience using command mkdir directory_name(NodeProjectPractice we created here).

Step-3

Change the directoy and go to NodeProjectPractice directoy using command cd NodeProjectPractice.

Step-4

We run a command npm init in command prompt to create a package.json file Use of Package.json file in nodejs It basically contains the name of the project,current version of module,script,description of the project,license,author of the project.It consist of starting point of the module(“main”),dependencies used in the project script used ,repository link in the project.

Step-5

Next step is to create a javascript file by name app.js and print hello world using console.log

Step-6

To print hello world in command prompt use command “node app.js”.

Step-7

To install Express npm install express — save step-7 We should import express using require. step-8 Next to import index.ejs page in app.js(controller file).

Step-8

var express=require(‘express’);

var bodyparser=require(‘body-parser’);

var mongoose=require(‘mongoose’);

var app=express();

mongoose.Promise=global.Promise;

mongoose.connect(‘mongodb+srv://harsh:h@cluster0-lyhzc.mongodb.net

/test?retryWrites=true&w=majority’);

var nameSchema = new mongoose.Schema ({

email:String,

phone:Number,

name:String,

pass:String });

nameSchema object is created using Schema constructor of mongoose and property is assigned.

var Use = mongoose.model(“Use”, nameSchema);

app.use(bodyparser.urlencoded({ extended: true }))

//here the encoded data is decoded by body-parser //body-parser takes the data we submit ,convert it in json format and put it in req.body app.use(bodyParser.json());

app.set(‘view engine’,’ejs’);

app.use(“/public”,express.static(‘public’))

app.get(‘/’,function(req,res)

{ res.render(‘index’);

})

app.post(“/adddata”,function(req,res){

var mydata=new Use(req.body);

mydata.save() .then(result=>{

res.send(“item saved to database”); }) .catch(err => { res.status(400).send(“unable to save to database”); }); })

app.get(“/users”,function(req,res) {

Use.find({},function(err,result){

if(err) return err; res.json(result); }) });

app.listen(7000,function(){

console.log(“app is runinng at 7000……”);

});

--

--