Create node js server and start express js app from scratch

Create node js server and start express js app from scratch

Requirements :

  • NPM ,

  • NODE JS

Install above requirements on your system .

Node Js is an open-source server environment .Node.js is cross-platform and runs on Windows, Linux, Unix, and macOS. Node.js is a back-end JavaScript runtime environment. Node.js runs on the V8 JavaScript Engine and executes JavaScript code outside a web browser .

Create Node Js Server

create file for node js example : index.js (.js is must) import http

http module for create node js server

var http = requir('http')

http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/html' })
res.end('hello world')
}).listen(3000)

listen 3000 is port

after entered above code in index.js then run this node index.js command on terminal now server is started, load this link localhost:3000 on browser

Create Express Js app from scratch

Express Js is an framework for node js its helps to reduce node js backend code .Express js famous node js framework for backend developers .Here iam telling i how to create simple express js app from scratch .

first step create a folder for express js app then open terminal in created folder and type in terminal npm init after show this

nodeJs.png

fill package name

and then install express and nodemon using this npm install nodemon express command

then create file for express js example app.js (.js must) an add this "start" : "nodemon app.js" to package.json in scripts, here app.js is iam created express js file

nodeJs2.png

then add this code to app.js

var express = require('express')
var app = express()

var port = process.env.PORT || 3000  

app.use(function (req,res,next){
console.log('midddleware')             
next()
})

app.get('/',(req,res)=>{
res.send('HOME')
})

app.get('/demo',(req,res)=>{
res.send('HI')
})

app.listen(port,(err)=>{
if (err) console.log(err);
    console.log("Server listening on PORT", port);
})

after add above code then run this npm start command on terminal and run localhost:3000 on browser

middleware work on every server calls