NODE JS Flashcards

(12 cards)

1
Q

what is node js?

A

summary: it is a run time envirnment to run js code outside of browser

eariler browser were the envirnoment to run our js code outside of browser our js code doesnt run.therefore node is runtime envirnoment i.e it give envirnoment to js for running it outside of browser.

note : though this envirnment can run js code like console in browser but documnet cannot be accesed as the document was created in browser and we excueting outside the browser therefore instead of document object we have global object in which we make manupilation

2 imp points:
1) used for various purposes but famously used for sever side programing
2) its not a language , library, framework its a runtime envirnoment ot run js code

thererfore it is one of the most popular technology used to build backend

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

what node Repl

A

Summary : Node REPL is a shell in terminal that allow you to run js code. To start it use the command “node” in terminal and once started terminal commands like ls,pwd,cd wont work to exist perform any one action ctrl+c(twice) or ctrl+d(once) or .exist

REPL stands for Read, Evaluate,Print,Loop Therefore Node REPL is an interactive shell that lets you run JavaScript code line-by-line.

using node command in terminal triggers node REPL i.e js envirment start to run and if we write js code then it get excueted

note : once typed node the node envienment opens up and terminal commands wont work in terminal now as js does have any meaning attached to them if you want to run the terminal commands then exist the node envirnment and run the commands

To Exist perform any one of the following
1) Press crtl+c(twice)
2) Press crtl+d(once)
3) .exist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

how to Run JS code file in node : from node file lecture

A

to run js code in node make sure of two things:

1) present in the same directory in which the js code file is there
2) run the command “node filename” , here filename is the name of the js code file you want to run

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Process in JS code

A

summary: process in node is a object that contain all current node js process being runned : one of them is process.argv - it returns an array of all the command line input(argument) passed to a program

Process is special object in node that contain all information about the current node js process also it provide control(allow us to manupilate them) over them
it contain various methods and properties just like an object which can be accessed using process.methodName (here methodName is the name of method in the process that we are trying to access)

one of them is process.argv
it returns a array that contain command line argument passed to the program when js code was runned
here command line argument means the agrument that were passed to program as arugment through command line these do not include any argument except commad line

example :
in vs code js file
console.log(process.argv);

in command line
command line boilerplate > suryansh yash sumit tansih hiten arpit rohan manish
[
excuetable path for node
current file directory of js file // these 2 are deafult prinited even if there is no arguments
suryansh
yash
sumit
tanish
hiten
arpit
rohan
mainsh
]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

what is Require and Export in JS and how it is used to export another file code to current program give example?

A

summary: require and export are feature of js that allow us to share/use existing code in one file to another. by default export return an object (explicity made string,array,number etc) synatx is module.exports=things to export
require is built function in js to inculde exported code in the current program if there is no export and only require then it returns an empty object {} syntax is datatype variable_name=require(“./filename or foldername”);

whenever we have rquire the npm packages then we dont need to write ./ we can write directly there name

Export : is a object(can be made explicity string,number etc but by default its an object) that contain all the things that one file want to send to another

syntax: module.exports= things to export to another file;

require(): a built in function in js to inculde external module that exist in another file in the current program

syntax : cosnt req= require(“./FileName”) //FileName is the filename of the program from where we are exporting the code make sure the both the program are in same directory otherwise you got to write all full path

Note: in cases where we there is no export but we require it in our current program then an empty object is returned {}

example:

1) Math.js

Const PI=3.14;
Const sum =(a,b) => {return a+b};

// way 1 : making obj of items to export and then exporting it

let obj={
PI:PI,
sum:sum
};

module.export=obj;

// way 2 : another way was make the module.export as object

module.export={
PI:PI,
sum:sum
};

// way 3 : directly using module.export in declaring

module.export.PI=3.14; // here when using with directly with declaring then module can be omitted therefore it can also be written as export.PI=3.14;
module.export.sum =(a,b) => {return a+b};

2) script.js

const req=require(“./Math”);
console.log(req);
// we can directly access the method like console.log(req.sum(2,2));

find why it not running your vs code : it was not running because of syntax error i.e i wrote export instead of exports

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

require and exports in directories

A

summary: this can be done by making index.js file in the folder from which we want to export code the index.js file will require all the code that we want to export from this current folder files and then export it .

require process for the different folder in which we we want to send code is same as above but there will be foldername called in require

lets say we have one file and one folder script.js and fruits respectivity we want to use fruits folder codes in script.js but hte problem is that fruit has multiple js file whose code we want to use so we make an index.js(this name is compulsory) file in fruits that reqiure all the codes from the each file in fruits and then exports them in form of array

example: in index.js of fruits

const apple=require(“./apple”);
const bannana=require(“./bannana”);
const mango=require(“./mango”);

module.exports=[apple,bannana,mango];

in script.js

const fruits=require(“./fruits”); // here fruits is the folder name from which we want to get our codes

the sole purpose of index.js file is to do this require and export thing for the folder in this case fruits

how it work: it works in 2 steps
1) which folder we require in our file the control goes in that folder and search for index.js file hence index.js act as an entry point
2)then export then code exported in the index.js

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

what is npm

A

summary npm is node package manager which has 2 main functions 1) maintian the libray of packages 2) provide command line tool to install or to do manupilation in the package like changing the versions

npm is standard package manager for node js npm stands for node package manager
node ke packages ka manager hai
even though not a libray but can image as libray of packages , package are code written by other that we can use literal meaning code wrapped in gift so we can use npm to unwrapp and use it

npm is:
1) library of package: which contain various package so that we can use them
2) command line tool : its also a tools through which we can access these packages

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

brief notes on installing npm

A

summary : to install any npm package we write npm install packageName or npm i packageName once install there will be 3 files generated 1)node_module:contain all installed dependenvcy2)package-lock.json: contail exact version of dependencies and sub dependencies installed 2)package.json: contain functional metadata above the project like name,version,description etc
npm init: to amke package.json file for your project and npm install to install all the dependencies we require at project (make sure package.json file is present)

synatax to install package through npm

npm install packageName or
npm i packageName

example : npm install figlet

folder in which we are install the package is very important as package has limited scope till the folder there are installed in

in normal case this wont run because window dont allow powershell to run script for security purpose so open powershell as administerer and run this command for tempory turn off i.e security turned off only for this window of powershell

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

after install you get 3 file

1)node_module : contain all the packages(dependeny) installed a dependeny is software or code without which our project code breaks like an api is dependeny if it stops working then our code breaks

node_modules: It’s the folder that physically stores all the installed dependencies (packages) for your project.

2)package-lock.json : contians version of all package (dependency) and sub dependency like contain all the verison of figlet i have installed and if figlet is dependent on some software then it will note there version also example of figlet is built with express then if express fails then figlet fails there this json file note the veresion of express also to keep track

package-lock.json: It’s a file that records the exact versions of every installed dependency (and their sub-dependencies) so that if someone else installs the project later, they get the same versions.

In simple words:

node_modules = the actual downloaded stuff

package-lock.json = the detailed receipt of exactly what and which version you downloaded

3)pacakage.json: contain functional metadata about the projects like name,verssions dependency on which our code dependes

it tell what i want to smothlly run this project

you can create package .json file by npm init command once typed it will ask name author version description lisence etc that you can give

only package.json file is shared between developer as once we have the package.json file simply by typing npm install node will download all the dependency mentioned in the package.json file

Super quick memory hack:

package.json = “What I want”

package-lock.json = “Exactly what I got”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

how to install packages gobally

A

note : installing packages locally is the best practice
but in case you have install packages gobally then you got to run two commands

1) npm install -g packageName // -g stands for gobal
2) npm link packageName

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

importing modules

A

summary : it es6 feature of js export syntax is export datatype variable_name=things to import;
importing synatx : import{variable name of files to import} from “./filename”;
selective importing is allowed in import feature and it work like asynchronous

import is the es6 feature of js that act as an subsitute to require built in function note either we use import in whole project or require we dont use both as a good programmer

for doing this

// exporting syntax

export datatype variable_name=thing to export;

example : export const name=”suryansh”;
export const age=21;
export const gender=”male”;

// importing synatx

import {variable name of files to import} from “./fullName with extenstion”;

if there are multiple file export and we only only want 2 file then selective importing is possible through import feature

import{name,gender} from”./fruits.js”;

require vs import

1) selective loading is possible through import but not possible through require as require import whole code in form of object whereas import can selectively import files which can save memory
2)require is syncrohnous and import is asyncrohnous means it can import in random order and does not require to follow specific order ex if 123456789 file written as export then we can selectivly import 4,6,9 as order is not followed therefore it becomes asynchronous

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

nodemon

A

nodeman is package in node js that automatically refreshs the sever after a every change we save

npm install -g nodemon

we generally install nodemon gobally so that we dont have to install it evry time locally

to run the file through nodemon we write

nodemon index.js(file name we want to run)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

path parameters and query parameter

A

path parameter are dynamic(changeable according to client input) variable which act as an placeholder to store the revelant and specific part of url

simple analog : If your URL is a sentence,
then Path Parameters are blanks you fill.

example : there more than million insta accounts so we cannot type custom path to each user name like

app.get(“/custom username path”,(req,res){
//do something;
})

this will cost time and memory as we will need to make millions of coustom routes adn it make our code bulky instead we can use path parameter that act like variable to store this username when client sends a requests

to declare path parameter we use “:” colon and then varibale_name of path example

app.get(“/user/:Username/:UserId”),(req,res){ //do something
})

here in the url localhost/8080/user/suryansh/123

suraynsh and 123 are username and user id respectivily

these value by client are stored in the req.params object where req is object of express and params is the property to access the specific property(variable) we write

req.params.UserName
req.params.UserId example

// here down it can be /user/:username also
app.get(“/:UserName/:UserId”,(req,res)=>{
let username=req.params.UserName;
let userid =req.params.UserId; // note //this can also be written as let { //username,userid}=req.params;
console.log(welcome ${username} your user id is ${userid});
})

note : we need to type path parameter with url is compulsory missing them and simply writing them as localhost/8080/user will generate error

path parameter value are taken from the url when the client send the request

like path parametere there are query parameter and they are defined with “?” in the url they are not compulsory in the url like path paramter but provide extra information about whats the request

example/syntax :

app.get(“/user/:username),(req,res)=>{
//query parameter are not given int path name they are directy used in the callback if user mention them in url then they have a value otherwise they are empty objects{}

let username=req.params.username;
let filter=req.query.filter
let sort=req.query.sort
});
url request is send as follows :
http://localhost:8080/user/suryansh/123?likes=34343&comments=13233

note only one “?” is allowed for query if you want multiple query then sperate them using & operator also query parameter are send in the form of key = value pair

final example:
app.get(“/user/:username/:userid”,(req,res)=>{
let {username,userid}=req.params; //this is called deconstruing in js learn it
let likes=req.query.likes;
let comments=req.query.comments;

res.send(`hello ${username} your user id is ${userid} your likes and comment count is ${likes} and ${comments}`); })

we can aslo send the html response

res.send(<h1>hello ${username} your user id is ${userid} your likes and comment count is ${likes} and ${comments}</h1>);
//note backtick(`) is compulsory even if you are sending html tags

what is clietn dont send any query then we return empty string or we can write

if(!likes&&comments){
res.send(“nothing serached”);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly