JavaScript Interview tricky questions
React Interview Questions
JavaScript DSA
JavaScript interview questions
JavaScript Clean Code
funny and tricky JavaScript examples
You Don't Know -JS
To crate a node server in Node js we need two things
-
Request Object : handle client
-
Response Object : handle server.
Steps to crete node server:-
create a file server.js/index.js : : most important file which intialises the server or which set-ups server.
No Application is possible without node-server file.
step1:-
create const reference for http module.
const http = require('http');
step2 :-
using http Object createServer Interface.
http.createServer((request,response)=>{
});
step3:-
Now set up a port where you want Your server launch.
Never use following
port => 80 => Apache
port => 3000 => React
port => 5000 => Django
Note :: Never use reserved Port
Use other port like ๐๐ป
8080 => by-default port.(mostly used)
7080
7000
const PORT=8080;
http.listen(PORT,()=>{
console.log("Server started successfully at port"+PORT);
});
Complete Code ๐๐ป
//http require
const http = require('http');
// port
const PORT=8080;
//create server using http Object
const server = http.createServer((request,response)=>{
response.writeHead(200,{"Content-Type":"text/plain"});
response.write("<h1>Hello Coders</h1>")
response.end();
});
//listen to the port;
server.listen(PORT,function(){
console.log('Server Started at PORT ='+PORT);
}); //Asynchronous : callback
in sort for use below command
require('http').createServer((rq,rs)=>{
rs.write("<h1>Hello Baccho</h1>")
rs.end();
}).listen(8080,function(){
console.log("Server Started");
})
- You should have a Array of Json Object which can be send as response to server.
- set the Content-Type : application/json
- use JSON.stringify() to encode the json to string : Serialization.
Note : : Why we are using JSON.stringify, because of two reasons
- response.write() only takes string input
- Browser only Understand text or tag.
Code ๐๐ป
let student = [
{
"id": 1,
"name": "XYZ",
"class": "10th",
"email": "[email protected]",
"mobile": "9999999990"
},
{
"id": 2,
"name": "ABC",
"class": "12th",
"email": "[email protected]",
"mobile": "9999999990"
},
{
"id": 3,
"name": "Raj",
"class": "Naam to suna hi hoga",
"email": "[email protected]",
"mobile": "9999999990"
}
];
require('http').createServer((rq, rs) =>
{
rs.writeHead(200, { "Content-Type": "application/json" });
rs.write(JSON.stringify(student));
rs.end();
}).listen(8080, () =>
{
console.log("Server Started at port 8080");
})
1. response.writeHead(200,{"Content-Type":"text/html"});
2. response.write("<h1>This is Heading</h1>");
Note here is problem :-
You cannot write lot of html code.
You can use template string and Write the web-page code
and you can then pass that variable as response to write();
Problem:-
Right now we are writting all data level code and design level code in server.js
data level => model
design level => View
hence we must organise the data in mvc design pattern to follow modular approach.
Controller
model
View
index.js or server,js
.env => configuration or Environment variable.
.gitIgnore
package.json
package-lock.json
This project structure is common for all, projects.
controller => folder mkdir
model => folder mkdir
view => folder mkdir
index.js => js file touch
package.json => npm init -y
package-lock.json => npm install
Note : : package.json will install node_modules folder if any dependencies are added in package.json
& please make use of git bash terminal
- module.exports = {}
- exports.var = var;
Note :: module.exports/exports both referes to global empty Object
this => {} => global empty Object.
module = {exports : {x:10}}
module.exports = {x:10}
module.exports.x=10
var x=10;
module = {exports:x}
module.exports = x;
In flexible there is no difference B/w module.exports and exports.
but in strict mode we cannot use exports directly.
it is because module is a mendatory, Object in strict mode.
but since module refer to this Object. you can pass varaible in following
1. module.exports = x;
2. this.exports = x;
3. exports.x=x;
|
this => module.
exports === module.exports : strict mode : off
exports != module.exports : strict mode : on
We know that,
m => model
v => view
c => controller
It is always better approach, to keep the different Js file with in different associated folder such that modularity of the project can be maintained.
StudentModel.js Model suffix => pascal case
StudentController.js Controller suffix => pascal case.
students.js =>view lovwecase suffix.
Note :: Template Engine
pug : students.pug
EJS : student.ejs
jade : student.jd
handlebars : student.hbs
mustaches : mts
These template files on views are called as partials.
Views
| partials
....template Engines.
| layouts
index.html,index.js
StudentModel.js
data of the Student model =>
Api call => student data.
var studentModel = {
students:[
{
"id":1001,
"name": "Prabhat",
"class": "Btech",
"stream": "CS"
},
{
"id":1002,
"name": "virat",
"class": "Btech",
"stream": "IT"
},
{
"id":1003,
"name": "Salmon",
"class": "BA",
"stream": "Hindi"
},
{
"id":1004,
"name": "Akash",
"class": "MBA",
"stream": "IT"
},
]
}
module.exports = studentModel
StudentController.js
const studentModel = require("./studentModel");
- data from model to controller
Response Object it must contain
1. code : 201
2. data : it can be array or object [], {}
3. status : true or false
4. message or comment : "Login Successfull","Oops something, went wrong".
5. error : by-default it will be false, if any error error message will be raised
let response = {};
try and catch.
let promise = fetch(url).then().then.catch((error)=>{
let responseError = error
});
JsonResponse = {
"code" : 404,
"message" : "Runtime Exception cannot Post data",
"data" : [],
"status" : false
"error" : responseError
}
response.writeHead(200,{"Content-Type":"application/json"})
or
response.writeHead(200,{"Content-Type":"application/json;Charset=utf-8"})
response.write(JSON.stringify(JsonResponse));
by default when you will be using express module.
you will get json() method, to print the output in pretty mode.
but we are not using "express" module hence, we need to use JSON.stringify() to print the output in pretty mode.
pretty mode in JSON.stringify() :-
JSON.stringify({name:"prabhat",class:"Diploma"})
output :
{name:"prabhat",class:"Diploma"}
pretty Output :-
you need to increase padding width or pretty width
JSON.stringify(object,null,Pwidth)
Pwidth = 1,2,..................n
standard : 4
JSON.stringify({name:"prabhat",class:"Diploma"},null,4)
Output :
{name:"prabhat",class:"Diploma"}
{
name:"prabhat",
class:"Diploma"
}