All language subtitles for [English (auto-generated)] Node.js and Express.js - Full Course [DownSub.com]

af Afrikaans
ak Akan
sq Albanian
hy Armenian
az Azerbaijani
eu Basque
be Belarusian
bem Bemba
bn Bengali
bh Bihari
bs Bosnian
br Breton
bg Bulgarian
km Cambodian
ca Catalan
ceb Cebuano
chr Cherokee
ny Chichewa
zh-CN Chinese (Simplified)
zh-TW Chinese (Traditional)
co Corsican
hr Croatian
cs Czech
da Danish
nl Dutch
en English
eo Esperanto
et Estonian
ee Ewe
fo Faroese
tl Filipino
fi Finnish
fr French
fy Frisian
gaa Ga
gl Galician
ka Georgian
de German
el Greek
gn Guarani
gu Gujarati
ht Haitian Creole
ha Hausa
haw Hawaiian
iw Hebrew
hi Hindi
hmn Hmong
hu Hungarian
is Icelandic
ig Igbo
id Indonesian
ia Interlingua
ga Irish
it Italian
ja Japanese
jw Javanese
kn Kannada
kk Kazakh
rw Kinyarwanda
rn Kirundi
kg Kongo
ko Korean
kri Krio (Sierra Leone)
ku Kurdish
ckb Kurdish (Soranรฎ)
ky Kyrgyz
lo Laothian
la Latin
lv Latvian
ln Lingala
lt Lithuanian
loz Lozi
lg Luganda
ach Luo
lb Luxembourgish
mk Macedonian
mg Malagasy
ms Malay
ml Malayalam
mt Maltese
mi Maori
mr Marathi
mfe Mauritian Creole
mo Moldavian
mn Mongolian
my Myanmar (Burmese)
sr-ME Montenegrin
ne Nepali
pcm Nigerian Pidgin
nso Northern Sotho
no Norwegian
nn Norwegian (Nynorsk)
oc Occitan
or Oriya
om Oromo
ps Pashto
fa Persian
pl Polish
pt-BR Portuguese (Brazil)
pt Portuguese (Portugal)
pa Punjabi
qu Quechua
ro Romanian
rm Romansh
nyn Runyakitara
ru Russian
sm Samoan
gd Scots Gaelic
sr Serbian
sh Serbo-Croatian
st Sesotho
tn Setswana
crs Seychellois Creole
sn Shona
sd Sindhi
si Sinhalese
sk Slovak
sl Slovenian
so Somali
es Spanish
es-419 Spanish (Latin American)
su Sundanese
sw Swahili
sv Swedish
tg Tajik
ta Tamil
tt Tatar
te Telugu
th Thai
ti Tigrinya
to Tonga
lua Tshiluba
tum Tumbuka
tr Turkish
tk Turkmen
tw Twi
ug Uighur
uk Ukrainian
ur Urdu
uz Uzbek
vi Vietnamese
cy Welsh
wo Wolof
xh Xhosa
yi Yiddish
yo Yoruba
zu Zulu

Original subtitles

this eight hour course will teach you

the fundamentals of node.js and express

so you can start creating backend and

full stack web apps using javascript

this course was created by john smilga

john has created a bunch of courses

including many of the more popular

courses on the freecodecamp youtube

channel

john's teaching is very hands-on so you

will create a bunch of projects while

you're learning what's up everybody this

is john from coding addict and welcome

to node and express tutorial video where

we'll cover fundamental building blocks

of node and express js framework now

since i want everyone to be on the same

page we'll start the series with node

and express fundamentals and gradually

move to more complex topics we will

build complex rest api with express.js

as well as full-blown mern application

in this comprehensive node.js course

you'll not only learn fundamentals of

node but also many related technologies

like express.js framework mongodb

as well as mongoose the main goal of the

course is to show you how to build

modern fast and scalable server-side web

applications with node

like in all my other courses to solidify

our knowledge we'll build a bunch of

cool apps and go through the steps of

deployment as well

lastly let me just say this if you're

like me and you enjoy learning new tech

by building projects

instead of going through the slides you

will enjoy this course

all right and let's start by answering

the most obvious question first what is

node.js

and even though there are plenty of good

answers out there the one that i like

the most is this one

node.js is an environment to run

javascript

outside of the browser

node.js was created in 2009 and it's

built on top of chrome's v8 javascript

engine

as you probably are aware of every

browser has an engine a tool that

compiles our code down to machine code

and chrome uses one by the name of v8 in

extremely simple terms the creator of

node ryan dahl ripped out the v8 engine

and build node on top of it since the

moment it was created node has evolved

tremendously

and while there are many things to like

about node i particularly enjoy large

community around node since that

tremendously saves time on feature

development as well as the fact that

with the help of node it's never been

easier to build full stack apps since

both front end and backend are

essentially built in the same language

and you guessed it that language is our

beloved javascript as far as course

requirements go

there are not that many

my expectation is that you are familiar

with basic html elements simple css

rules and have general understanding of

javascript especially es6 callbacks

promises and a sync await

since this is a node course

and i already have tremendous amount of

node content to cover i'm not going to

spend too much time on javascript

language fundamentals

while you can still follow along with

the course without knowing basics

it's crucial if you want to understand

how stuff works behind the scenes

as a side note if you need to brush up

on the javascript fundamentals i have a

youtube channel called coding addict

where i post a bunch of cool javascript

related content

specifically you might be interested in

js nuggets playlist where i cover a

bunch of useful es6 features as well as

asynchronous javascript topics so if you

need to jog your memory on javascript

fundamentals i suggest going to youtube

look for the channel by the name of

coding addict and then more specifically

the playlist by the name of javascript

nuggets when it comes to course

structure it goes something like this

in first section we'll get familiar with

node.js

as well as my dev setup

in the second section we're going to

install node.js and quickly cover some

general differences between browser.js

and node.js

then we'll spend some time on node.js

fundamentals in section 3 and after that

we'll learn what is express.js in

section number four

and once we're done with node and

express fundamentals so once we're done

with pleasantries

then we're after the races where

effectively in every section after that

we will build a bunch of cool node.js

apps all right and before we install

node let's quickly cover some major

differences between browser javascript

and node.js so essentially how node.js

apps are different from the browser

javascript apps

and let's start with the biggest one

when working on node.js app you have no

access let me repeat no access to

browser apis

since well they don't simply exist in

node there is no browser so there's no

dom there's no geo location no fetch and

all the other cool browser goodies you

see unlike browser apps that are

interactive for example user clicks the

button or toggles the nav and that sort

of thing

with node we build server side apps

and i know it's hard to picture that

right now but

our node apps will only consist of pure

logic without the graphical interface on

that note you know how in browser apps

we use a bunch of cool things available

on the window object

yeah sorry to break it to you but that's

also not available in node

so at no point in the course we'll write

document.queryselector

all right

and once we have covered things that

node.js does not have let's switch gears

and see some of the goodies that node

has to offer for example unlike browser

we can access file system

info about our operating system respond

to network quests just to name a few

also another major benefit of node is

the fact that it's based on versions

so unlike browser apps which depend on

the user's browser

our node app depends only on node.js

version it was built in

so in other words if we build a browser

app

and if our user's browser does not

support a specific feature

it is our responsibility to fix it

otherwise our app might have bugs

correct but when we're done building our

node app there's no rule that we have to

upgrade to a newer node.js version

and possibly break our app

we simply can keep running our node app

in the version it was built in and

without any worries go on about our day

lastly unlike browsers where modules are

optional

in node.js you have access to modules by

default and it's hard to imagine a node

app where you're not going to use them

as a quick side note under the hood

nodejs uses common js library for the

modules and while the general idea is

exactly the same as for the es6 modules

that we use in the browser syntax is a

bit different

as far as the install it's as

straightforward as it gets

just navigate to nodejs.org pick a lts

version

answer yes to all the questions

and if you don't get some weird bugs

congrats you have installed node

in order to check if everything went

correct just type node

version in your terminal

and you should see the version number if

you don't you'll have to troubleshoot

the error now as much as i would like to

help

when it comes to install it's impossible

for me to troubleshoot your local setup

so when it comes to troubleshooting

install errors i strongly suggest using

your favorite search engine instead

typically within a matter of minutes

you'll see a bunch of useful solutions

to your exact problem

lastly let's also talk about versions as

you can see at the time of the recording

i have two options

14 lts

or 15 current one

if you read the note docs you'll see

that for production apps they always

suggest using lts which stands for long

term support and therefore i will also

suggest the same but as far as tutorial

i don't think you'll have any issues if

you use the current version instead now

also since you're watching this in the

future your version number most likely

is going to be greater than 14 basically

greater than mine i definitely suggest

installing the lts option

that's offered to you instead of

downgrading to my version and if you're

stressing about content being out of

date

let me assure you that everything we

cover in the course will work perfectly

fine with your current note version

and eventually if some bugs do creep in

i will definitely update the course

content so long story short just install

your current lts version whatever it is

and you'll be in good shape so in my

case it is 14

i have two big buttons and of course

since i would want to go with lts i'll

click on left one

then notice we are getting the download

package and now i just need to go to my

downloads

and then crack it open

and then like i said we just need to

answer yes to all the questions so we go

with continue

continue

and yep i would agree

and again we just install and then we'll

be prompted for our passport

and once we add that one we should be in

good shape and then like i said once the

install is complete

and yep we'll move this sucker to the

trash then if we go to our terminal and

if i massively zoom in

and if i type node

version

there it is i should have my version

number which in my case of course is 14.

if you also can see the node version in

your terminal you are in good shape and

you can continue

with the videos

if not

please troubleshoot it because otherwise

everything we're about to do next is not

going to work since you haven't

installed node

on your computer

install is complete hopefully we all

have node on our machines now what

what do we do

for contrast with vanilla.js it was

somewhat easy right we create index.html

jam our javascript code whichever way we

prefer and browser does the rest it

evaluates our javascript code but

what about node how do we get node to

evaluate our code

and effectively we have two options

a repl which stands for read eval print

loop and cli executable which just means

running our app code in node if i have

to be perfectly honest reply is for

playing around and cli is essentially

for everything else in fact this is

going to be the first and most likely

the only time we'll use a rebel in this

course and after that cli is going to be

our best friend how do we spin up the

rebel well

we go to terminal and in terminal we

simply type

node and then no arguments nothing we

just press return or enter however you

would like to call the button and that's

it now notice we have this little angle

bracket that just means that we are in

the rebel and once we are in a rebel we

can do reply things what would be a

first ripley thing we can do well we can

simply type our name so cons

and the name is equal to john

and there it is of course now i can

access name and my name is john

as you can see

you're not going to write anything

serious in here and if you have written

any vanilla javascript apps you know

that of course we can also do the same

thing in a browser console

so we can also evaluate some code there

but of course we're not going to write

anything serious in a browser's console

so the same thing is for reple yes we

can come here we can play around but

when it comes to serious applications of

course you'll pick a cli executable

instead and in order to close the repo

we simply go with control and c

and as you can see we have suggestion

that we need to press it again and now

of course we're out of the rebel not bad

that bad we now know how the ripple

works

but what about a more serious node

application

how do we get node to evaluate our code

well we would need to start by creating

a project right so back on my desktop

i'm going to create a new folder

and surprise surprise i will call this

tutorial why well because we'll do

tutorial things

and i'm going to say tutorial now of

course if you want you can add node but

i'm just going to leave it as a tutorial

and then of course we'll have to use our

text error in my case like i already

previously mentioned i'm using visual

studio code

and my preferred method is just drag and

drop

and then instead of the folder what i

would want is to create a new file and

this is the case where you can literally

name it whatever you would want and in

my case i'm going to go with app and js

and in this app.js okay now we want to

write some more serious node program and

the program is going to be following

where there is a const so there's a

variable by the name of amount and as a

side note i'll make this bigger and i'll

probably bump up the font size just so

we can see a bit clearer

so we're gonna go with const and not

also close the sidebar hopefully you see

that i have the file by the name of

app.js

and like i previously mentioned we're

going to have a variable by the name of

amount and it's going to be equal to 12

and now let's set up a if condition

where if amount is less than 10 then we

simply cancel log small number and

otherwise we'll just say that the number

e is large so we go with if

and we're looking for amount

is less than 10 and if that is the case

we go with console log and we'll just

say

small

number

and otherwise if it is of course equal

or bigger than 10 then we go with

console log and we say

large

number

and at the end of the day we just write

console log hey it's my first note up as

you can see an extremely complicated

functionality and in this case i'm just

going to set up the template strings so

you understand that of course we can use

them here as well i'll say hey it's my

first

node app and if you want of course you

can jam the hello world there somewhere

as well since that is the traditional

approach with the first program

and then in order to execute this code

we effectively have two options i can

navigate back to my terminal

and i can zoom in like so and of course

now i'm in a root so i would need to

navigate to the desktop and probably the

fastest way is just typing cd and drag

and drop

my folder here okay so now as you can

see i'm in the tutorial and in order to

execute my code i just need to type node

and then app.js now keep in mind that

technically i could have done that from

the root

we just need to provide the full path

where i go to users blah blah blah and

then tutorial and of course the file

name is app.js and let me bump up the

font size even more and the moment we

run it check it out we have large number

and hey it's my first note app now if

you don't believe me

we can go back and we for example can

say that the number is nine

and of course again we would need to run

the code

and we're gonna go with node and then

app js beautiful we have small number

and we still have our hey it's my first

node up again the whole point of this

line here is just to showcase that not

only we can use quotation marks but also

we can use the template string as well

so that's one option but if you're

familiar with vs code you know that it

has this cool feature of integrated

terminal where effectively we have our

terminal

but

it is right away pointing to our folder

so we don't need to do this whole dance

where we navigate to the folder and then

run the app we simply can open this up

and the shortcut is control and tilde

and also keep in mind that of course you

can navigate through the tabs the

problem is that i always forget where it

is and effectively we need to go to view

and then you're looking for this

terminal command here

as you can see this would be a shortcut

and tilde and in here we have nice

suggestion that we already located in

tutorial folder and what do we need to

do well again we just go with

node

app.js why well because that is my file

name so for the remainder of the course

i'll use the integrated terminal that

comes with this code just understand

that both of them effectively do the

same thing and there it is now i run

node app.js because that of course is

the file name and i have small number

and hey it's my first node app and

that's how we can evaluate a more

serious code using node as i note if at

any point during the course you need to

compare your code to mine just navigate

to website

johnsmilk.com and the website is

johnsmega.com and then either in the

project page or in the homepage you'll

find node express tutorial project so in

the homepage you'll find it in the

latest project so just keep on scrolling

but if it's not here it's definitely

going to be in the projects page and you

can even filter it in order to save some

time so look for node in here like i

said the project name is node express

tutorial and not any of these links

will get you to the repo and at this

point you can either clone it 4k

or just simply download and you're

looking for this node tutorial and in

here you'll find

all the folders as well as the files now

keep in mind that eventually when we

start working on express

we'll have to get this repo anyway

because i'll use it for starters since i

have prepared some assets for you some

assets that we're going to use in our

examples so this is really up to you if

you want you can get it right now just

keep in mind that you'll have to get it

later anyway and once we have executed

our first code in node

let's quickly cover the concept of

globals

or global variables in node

and the emphasis is on the word quickly

yes there are more global variables

available but the idea

is not to spend half an hour in slide

bill instead i would want to give you a

general idea

and as we progress with the course don't

worry

we will implement them

and that way you can right away see them

in action not just some random general

description

and before we continue let me just

mention

that throughout the tutorial

the code from the previous video

i'm going to save in a file so for

example remember our first

complex app

with a mount and all that

so what i did

i created a file name by the one

hyphen intro js and then i just copy and

paste it this is what i'm gonna do

throughout the no tutorial part of the

course so that way you can always have

access to the code and if you ever need

to you can jog your memory now if you

don't want to use my one if you're

adding your own comments and all that

i would also suggest doing that where

essentially just create a file just dump

it and then that way you are slowly

progressing on the course and if you

ever need to go back and refresh your

memory you always have that option and

keep in mind that

if you would want to run this file you

simply go with node and then whatever

the file name right so in my case that

would be one

dash intro

js again i'm going to keep on numbering

them because i'm just annoying that way

but you don't have to that is really up

to you so back to the globals

when we work in vanilla.js applications

we know a

very cool thing is the fact that we have

access to the window object and the

reason why it's so cool because in the

window object we can get a bunch of

useful things right so for example we

can get a query selector so i can select

a node

i can get built-in fetch

and hopefully you get the gist

now i don't want to rain on your parade

but

you know there's no window

why well because there's no browser so

there's no window object so if you'll

try to access window

node will spit back the error and most

likely your app will crash

now there are some globals of course

there is this concept of global

variables and essentially what global

variables means that

anywhere in your application you can

access them so no matter how complex my

application gets

how nested it gets or whatever

i'll always have access to those

variables and again let me repeat these

are just some of the variables of course

there's more and i'm not going to spend

hours and hours talking about them i

simply want to give you a general idea

and then like i said we'll start using

them and you'll see them in action and

in my opinion

that's just going to make it way clearer

about what in fact they're doing and

some of the useful ones we have their

name so that would be underscore

underscore their name

just going to give us path to current

directory then we have also underscore

underscore filename which as you can see

is going to give us a file name then we

have require which is a function to use

modules

as well as the module that would be info

about the current module now these two

will literally cover them

in the upcoming videos because our next

big topic is going to be modules

so for time being

just remember that we have require and

module and you'll see them in action in

no time and then we have a very very

very useful one and that one is a

process and why it's so useful because

it gives us a info about the environment

where the program

is executed because we need to keep in

mind when it comes to a node app

at the moment yeah we're executing that

on our machines

but

when you deploy for example your api so

for example your server right where is

it sitting it is sitting on digital

ocean or herald core or whatever so that

of course is already a different

environment

and of course based on that environment

you can

make a bunch of decisions in your

application

again

if you'll take a look at the process

right now it's just going to be a

giant object

of gibberish data but trust me as we're

progressing we the course

will find a bunch of useful properties

that we'll implement in our application

now any of them you can simply console

log and you'll get that useful data so

you can just run console log and then

for example their name again i'm not

going to cancel log all of them probably

the biggest one is going to be the

process like i said you'll get a bunch

of properties that at the moment

will look like a gibberish and i simply

need to save and of course then we go

with

node and app.js we run that and there it

is now of course this gives me the path

so

if you're interested of course you can

console log rest of them

as well

but

in my case i'm going to stop

with their name now also very quickly

yes you have access to the console

so as you can see in order to cancel log

we have to use the console so that is

also something that is available

globally then just like

in the event ljs we have set interval as

well as set timeout so you can run these

ones and i'm not going to run both of

them but i'll show you set interval very

quickly just so you don't think that i'm

cheating

and the way it's going to look like of

course we have our callback function and

then i'll say that my interval is going

to run every second and i must type

hello world otherwise

well what kind of tutorial is this and

again we simply go back to node and then

app js and as you can see now

after every second i have hello world in

console and in order to stop it remember

the command was ctrl and c

and before we move on and start talking

about the

modules let me also mention something

else

where essentially we don't need to type

node and then app.js you can simply

write

node and then app however throughout the

course i'll probably keep on typing js

just because i'm annoying that would be

the first thing now the second thing and

this is not a node thing this is

actually a terminal

if you don't want to type it you can

simply go back to the previous command

and in order to do that you need to

press on arrow key up and check it out

the moment you press notice that was my

previous command

and then i have one before that so in my

case that is node and then app.js again

you don't need to add that just

extension but probably i will

and then you just go back to the

previous command and then press and

again you just execute that command and

of course if you want to clear the

console again this is not a node thing

this is a terminal i just type clear and

lastly

to answer the question that's probably

bugging you the most we always have to

just type node and then the file name

because as we're going to be testing a

special in tutorial it will probably get

annoying and the answer is yes

but only for now

once we learn about npm

the external packages which at the

moment i fully understand doesn't make

any sense at all then there's command

that effectively will restart our

application so we'll have to install

some

third-party module some external library

and that will do the job of restarting

the application for now yes all

throughout tutorial up until the point

where we cover that external library and

external libraries in general yes we'll

have to type node and then whatever is

the file

i know it's a little bit annoying but i

just don't want to skip ahead i want to

get us there with a full information of

what is happening so with this in place

with clear understanding of the

global variables in node now let's move

on to our next topic which is going to

be modules in node beautiful

and once we understand the globals in

node now let's talk about the modules

and first let's return to this command

notice we have here

node and then app.js

probably the question

that you have

is well does that mean that all my

application

needs to be in this one file

and the answer again is yes and no

yes you'll execute one file

but you'll split your code in modules

otherwise that would be literally insane

to jam all your code in one file

and effectively i'll just show you with

an extremely complex app and of course

extremely complex is in the air quotes

right now

and you'll see why we'd want to use the

modules in the first place so in the

next video i'll give you official intro

with a bunch of gibberish and all that

but for time being let's just build

super complex

app and then see why i would want to use

those modules

in the first place and if you have any

familiarity with es6 modules if you have

worked with them in vanilla.js or in

react.js you're already in good shape

the syntax is going to be tiny bit

different because you know it uses

common js but the general idea is

exactly the same

and we start with a simple function by

the name of

say hi you guessed it and then this

function is going to be looking for the

name parameter and then inside of the

function what do we do

we simply cancel log and we say hello

there

and then whatever is the name of the

dude or the gal that is being passed in

as a parameter and of course we can

invoke it and i can say say hi and then

pass in susan for example

and in order to make this interesting

i'll set up some variables as well so

i'm going to say const john is equal to

john

and you guessed it

since there's a john there also has to

be a peter and hopefully you get the

gist so imagine we would have a bunch of

names and then we have probably more

functions than this one but for time

being this is just going to be say hi we

copy and paste we invoke this function i

guess three times one for johnny boy

one poor peter

and then the first one we already have

for susan and what do we do we run node

app or app.js we run that and there it

is now of course in our concert we can

clearly see hello there susan blah blah

blah now wouldn't it make sense if the

names would be separate as well as this

function or the future functions that

we're going to create would be in

separate files

and then we can access them all

throughout the application

and

that way of course we would have smaller

files and more structure to our

application and that is exactly what the

modules allow us to do

and that's why we'll move on and start

talking about the modules in the next

video

beautiful

and once we understand the main problem

with this code where again the moment

code is technically still tiny but as

you can see it is getting bigger and

more annoying with every line now let's

talk about the modules and i guess let

me just give you the

main idea first and then we'll talk

about the implementations and

all that good stuff so first of all what

are the modules again if you're familiar

with es6 modules you already have the

idea but essentially that is

encapsulated code

and the key here is that we're only

sharing what we want

so we're only sharing minimum how would

that look like in real life well i can

go here with secret

and then i can type here super

secret and then since this variable

is in this file

as we can see you can access anywhere

okay so by mistake i can just access it

i can override it now of course you can

make an argument that i mean it is made

with cons but hopefully you get the gist

this is available to me everywhere in

this file so once we set up the module

you'll see what are the differences now

node uses common js library under the

hood that's what makes it happen

and then every file in node is a module

again let me repeat every file in node

is a module so those super powers

that we will cover in just a few seconds

we have them by default we don't need to

do anything we don't need to go to the

store and buy some javascript code no we

just get them by default

and the way the modules work well we

simply need to create a new file right

and i'll right away

set up the names here because of course

eventually this code will be sitting in

the file name by the three hyphen and

then the module basics or whatever but

the names as well as the function well

it's going to be in a separate file so

what i'm trying to say is that in a root

of course there's no folders or nothing

so everything is rude i'm going to go

with four again i'm doing that because

eventually this is going to be three

hyphen modules something i'm gonna go

with maybe names or you can type first

module whatever you would want and i'm

just gonna go with names.js

okay awesome and then i'll take these

three

variables

from my app.js and i'll copy and paste

in the names and then also what i would

want is to set up one more file and of

course this one will be

five

and

i don't know we can say second module

or so i'll say here utils

something generic so we set that up

and now of course what i would want is

to grab this function

from the mgs and copy and paste in the

utils and now sixty four thousand dollar

question

is this app gonna work

or is it gonna break and of course the

answer is it's gonna break because we

have no access right now to say hi

or to john or peter so

why don't we

go to the names and console log

something and as i said yes you can

console log this in the app.js it is a

file so by default it is a module but

since we'll do most of our work in the

names and new tools first why don't we

go to names and that way we can also see

how we can run the file just by using

node and what i would want to console

log is the global by the name of module

so in the names

go below or above the variables doesn't

really matter

and go with console.log and then module

and remember to run node and then

whatever is the file name so in my case

it is four dash and then names

js you run this

and you'll notice something pretty

pretty cool

where we have the object

and in that object we have quite a few

properties now the one that i'm

interested in the most

is this exports one

and it tells me that this export is an

object

and the way the common js syntax works

whatever i'm going to dump

in that export i'm going to be able to

access anywhere in the application

so that's the key

remember we're only sharing the minimum

so it's up to us

to

set those values in that export object

we decide what goes in there previously

remember

secret was accessible

everywhere in my app.js

now in the names i can be hey you know

what john and peter yeah

i'm sharing them anywhere in application

we can access that but the secret

variable no this is just going to be

local so i'm going to add here i guess

the

comment by the name of local and that

way at least we understand so this is

going to be i mean i'm not going to use

global

but i'm just going to say that

share so we're sharing this with rest of

our application and then if i know that

this is a object

and it is sitting in the module how does

that work well we go with module

then it is an object so we go with

export

and we have multiple ways how we can set

this up but the most basic one will

simply say that yep it is an object and

inside of that object there's going to

be two properties john

and peter now i can probably already

guess that we're using a es6 syntax

since the key name is exactly the same

as the value well we can simply pass it

right so we have john and peter so now

what happens in the app.js we can access

them so i can go back and this is the

case where we'll need to run that

require remember in the globals we

talked about this function

so in order to share them we need to

use

module.exports and essentially i'm

setting up the object like so where i go

with whatever values i would like to

share now in order to access them

i need to go with require

and

i can assign it to a variable or i can

simply require now in our case we will

assign it to the variable and i'll use

the same type of syntax where i'm going

to go with names just so we can

console.log that

and this is going to be equal to require

so that's my function and as a parameter

we need to pass in where the module is

located

so where is this data coming from

and always always always always

you will be setting up your module you

have to start with dot now sometimes

your modules will be two levels up i

don't know three levels up whatever then

of course you'll start with dot dot but

you'll always start with this one dot

because there's also going to be a third

party modules and there's going to be

built-in modules in node and then we'll

use just these quotation marks again

super super important every time you

create your own module you'll have to

start with dot and then forward slash so

essentially you're giving a path now in

our case what is the path well i'm

looking for the names right so i set up

here the path and then if i cancel out

the names

i should see something pretty pretty

cool where i go with names

and there it is now i'm going to run

node and then app js now keep in mind

we're not running names anymore we go

with node and app.js now of course still

complains that we have no access to hi

let me comment this one out so let's say

node and app.js

and check it out now of course we have

the object

with john john and peter and peter

and we explicitly said what we would

want to export so we go with exports and

that way

no one has access to the secret one so

this secret one is only for this file

and of course we can do the same thing

in the utils as well right so we have

the say hi

and we go with module and export

and i can just simply set it equal to

now the reason why i was setting this up

as a object because i had multiple

things at john and peter and don't worry

in the next video i'll show you

alternative syntax how you can also set

this up but in this case i have object

and then of course i'm setting these

properties and i said note this is just

my preferred way of

actually using the exports again there's

multiple ways how we can do that and i

will cover the other ways in next video

but this is just my preferred method

that's why i right away set my exports

equal to an object and then pass these

two properties and in utils since i only

have one thing i'm just gonna go with

say hi that's it i'm saying

that i'm gonna be exporting my function

so say say hi like so and once i have

exported my function

now of course i need to go back to the

app.js

import my function the same name

and i'm going to go with say

say hi

and that one is going to be coming from

the different file of course so we go

with five

and then utils

and notice here how we don't need to

pass in the js if it is ajs file we just

simply omit the extension as long as the

file name of course matches

and then

i can remove now if you want you can

cancel log but i already know that i'm

gonna have the function over there i'll

uncomment my say hi

so now of course there's going to be no

error and let's make a clear console and

again we run

the node and then app js and there it is

now of course we have a different error

where it says well john is not defined

all right but i know that

john is sitting in the names right so

here we have multiple flavors either

you can destructure it

so instead of going with names i can go

john and peter that is definitely one

option or

i can go with property names right so i

can say

names and then john

and then the second one is names and

peter names and peter and now hopefully

everything works otherwise you're

probably thinking that i'm just messing

with you there it is now we have hello

there susan john and peter

and effectively what we did we separated

our concerns again the main idea is that

every file by default is a module and

then when it comes to a modules we are

in charge what we are sharing and in

order to

export or make it something available

from this module we go with module

exports

and then we just set up the

functionality whether this is going to

be a object that we're exporting or

we're simply exporting as a function

so we set this equal to

to the exports and if you're familiar

with es6 modules

as you can see this is very familiar to

the export

default and then whatever you're

exporting as default whether that is a

function whether that is a react

component or whatever notice i'm

exporting as default so of course

when i'm importing this

in this case app.js well i already know

that this is a function so i can name

this whatever i would want and the same

goes here

since i'm exporting this as object i can

call this shaken bait as long as i

access it later of course i'll be able

to access the property as long as the

name

matches to whatever i set up over here

so let me save this and now of course we

can talk about our next topic

all right so far we know two flavors

one

if we want to export one value

we just set module export

equal to that value and then of course

wherever we want to use it we just

import it

set it equal to some kind of variable

and of course

once we use that variable we have access

to that value

and the second flavor is if we have

multiple values

then we simply set module exports equal

to an object and then in that object we

set up the properties however there's

also another way how we can do that

and essentially it is called

export as you go

and the way it looks like

first i'm gonna set up a new file and

i'll call this six and i'll call this

alternative

flavor now again naming is really up to

you since that is the hardest thing in

programming

and then i'm going to come up with one

array and i'm going to call this items

and that will be equal to item one

and item number two

and then i'll set up a object and i'll

say const person is equal

to a object and there surprise surprise

we'll go with name property and set it

equal to bob

and i'm purposely adding multiple data

types

just so you don't think that we can only

export variables or functions

and in here we have two options

either

where we are setting up the

value in this case items i simply go

with

module exports and then whatever is the

name and of course in this case i'm

going to keep the items but notice the

syntax where instead of going with const

items i right away go with

module.exports

or if you are a true rebel you can do

something like this module exports set

up the property for example

single

person and set it equal to your person

object why we are able to do that

because if you remember in the previous

video when we console logged

module exports it was an object right so

what are we doing here we're setting up

a property on that object and set it

equal to an array

and here i set up another property and

just set it equal to a person keep in

mind of course i can still write simply

module exports and then the person

but since you might

sometimes see this type of syntax as

well i wanted to cover that and now of

course we save alternative flavor.js

and you're probably not going to be

surprised that if we navigate to app.js

and in this case i will call this data

because i'm getting a object and on that

object i have two properties and i need

to come up with some kind of name now as

always this name is really up to you

you can call it shake and bake you can

call it uncle bobby whatever you want in

my case i'm gonna go with generic data

we go with require again we're looking

for the file by the name of alternative

flavor

and

in this case i'm not gonna do anything

with it apart from console logging and

if i navigate back to my integrated

terminal and run

the node app.js

there it is of course now i have the

items as well as the single person

now please keep in mind one thing

where this syntax

whether the first line or line number

six

at the end of the day is exactly the

same like we're doing over here yes the

syntax is a bit different but at the end

of the day you just make these values

available somewhere else in your code

now just because i prefer this type of

syntax most likely throughout the course

you'll see this approach but

if you prefer this one instead

be my guest at the end of the day it is

your application and you are the one who

is going to be maintaining it and before

we move on to built in modules as well

as third-party modules let me throw you

a mind grenade

and i'm going to start by removing this

console log

in the app js like so and i'm going to

create a new file with the same exact

name a mine grenade as always

if you would like to call this

differently

that's totally your option

and i'm going to go with mine grenade

like so and js and in this file i'll

create some basic functionality and by

the way let me save app.js so let's go

with const

num1

is equal to 5 and then const num 2

is equal to 10. of course there has to

be a function that adds these values as

always with every tutorial so go with

add values just for the sake of it i'm

just going to go with good old function

keyword and the old setup meaning

not the arrow function syntax and simply

here we'll go with template string the

sum is colon

and then of course let's go for template

literal and we'll say num1 plus

num2

and

instead of setting up the exports i'll

simply invoke

add values

and now i'll throw you that migrate that

i was talking about where in the app.js

i'm not going to assign it to anything

i'll simply write require

and then we'll go with my grenade and

now let me comment out these three

since at the moment they will just over

populate the console and again let's run

node and app.js and once we're on our

code we can clearly see in the console

something pretty interesting where we

have a log of the sum is 15.

so what's happening over here

well

when we are setting up everything if we

have a function inside of the module

that we invoke yes that code will run

even though we didn't assign it to a

variable as you can see clearly here and

we didn't invoke that variable

and before we go any further let me

mention three things

first

it's not unique you can also do that in

es6 modules

and if you took my vanilla javascript

course you know that we use that

functionality number two yes throughout

the course here and there we will use

this particular setup now it's going to

be with third party modules and of

course once we get there i will remind

you about this setup so that's how it

works and third

i wouldn't suggest losing your sleep

over it

just please remember that when you

import a module you actually invoke it

and this is really going into weeds but

the reason why that happens is because

this code is not just exported on its

own

when the node exports this it actually

wraps it in the function so that's why

when you're required yeah you do invoke

the code if

you have some kind of function that

actually is executed here keep that in

mind not talking about exporting

something i'm talking about executing

function here and there and of course in

this case you need to use the

imagination that we'll do something way

more useful than this at this point

you're looking at it okay i could have

just set up that function in app.js and

you're 100 correct this is the place

where you definitely need to use your

imagination where of course the

functionality we'll use it for is going

to be way more complex but the idea is

going to be similar where we'll just

require some kind of module and behind

the scenes that module will do a bunch

of cool stuff okay that was fun we

created our first module and in the

process covered the general module

syntax and use cases as well

now what

well as helpful as our say hi function

is

some very smart people created way more

useful modules than that

and the good news is that we can start

using them right away

so what i'm trying to say here is that

node has bunch of built-in modules

that we can use freely in our apps

in the following videos we're going to

cover following modules os module so

operating system module path module file

system module as well as http module to

set up our http server and before we

continue let me just say this

i purposely cover only a few major

modules

and more specifically only a few

properties and methods provided by those

modules

you see the list of built-in modules in

node is quite big

and the amount of properties and methods

each module has

combined is of course even bigger

and as a result we could easily spend

the remainder of the course on just that

but is that really beneficial and of

course the answer is no

instead let's cover the general setup

first

and later as we progress with the course

implement some modules as we go

now if you're interested in more

properties and

methods built and modules have just

navigate to the docs and go nuts so if

at any point you would want to find out

more about specific property or method

or the built-in module in general just

navigate to nodejs.org

and then look for the docs

and again in my case

the version the long term support

version is 14

so i'm gonna click here but as you can

see we also have an option of going to

the older versions as well so as you can

see i can get the docs for the older

versions as well

but i'm just going to stick with my

version

and then be prepared to go nuts

if you enjoy docs

then you have yourself a big old party

where of course you can look for modules

and then each module has the properties

as well as the methods so of course you

can get a

extremely detailed information on the

properties as well as the methods here

in the docs

all right and once we have covered the

general existence of built-in modules

now let's take a look at few of them

and i'm going to start by creating that

file that i promised a few videos ago

remember when i was setting up the

modules i said that eventually there is

going to be a file by the name of 3n

modules and this one i would want to do

it together

just so you don't think that i'm not

fulfilling my promises so we're going to

go with module and then i guess

modules.js

i'll grab that i currently have in the

address it's pretty much everything

and we copy and paste and in this case i

also uncommented these say hi again this

all stays for your reference and you'll

have access to it if you navigate to the

github repo

so grab everything in app.js i'll

actually cut it out since we'll start

from scratch and copy and paste now of

course all this code is sitting in the

modules and just keep in mind that of

course we're still referencing the names

utils alternative flavor as well as my

favorite the mind grenade

and back in app.js

now let's start by taking a look at the

os module

and os module we built in module

provides many useful properties and

methods for interacting with operating

system as well as the server

and the general setup

for the built-in modules or even the

external ones that we're going to cover

a bit later

is going to be similar

where we're going to go with some kind

of variable

and in this case i'm going to call this

os for operating system then we're going

to go with require

and then in the require we'll have to

pass in the name

so since this is a built-in module of

course we don't need to install anything

just remember it later when we work with

external ones yes we'll have to install

that module first in this case it is a

built-in so we just go with os but again

let me stress something we're not doing

dot and then forward slash no we just go

with os so that way node knows all right

so you're looking for the built-in

module and

once we set this up

then we have multiple options

either you can access those methods by

just running this variable

so it would look something like this

where i go with os and notice

the moment i press dot

i have all these options so these are

the

methods and properties that i can use or

if we know that we want a specific one

you can simply destructure it here and

of course throughout the course i'll use

multiple setups just so you understand

that both of them effectively do the

same thing so here i have access to all

the methods and properties that this

module provides and of course now we can

go crazy for example i could get a

useful info about the current user which

of course is me so say info about

current and

user and you know what as a side note

i'll save here and i'll close all the

files it's just a bit annoying that i

have all those tabs open

back in the app.js

once i have a comment of course now i

would want to assign it to a

user and we'll simply go with os since

that is the name of my variable and then

method that i'm looking for is userinfo

i don't need to pass anything i simply

invoke it and of course since i would

want to see the result i simply go to

console log and then i'm looking for the

user and you can probably already guess

that we'll just run

node app.js and there it is now of

course i have a info about the user

which is me so this would be a home

directory this is going to be the

default shell and all kinds of useful

stuff

then i want to show you how we can get

the uptime of the system so effectively

how long the computer has been running

in seconds and i'll just add a comment

method

returns

the system

system

up time up time

in seconds

and

the way i'm going to run that i'll right

away set up the console log

just so you understand that of course we

have multiple options how we can invoke

those methods

you don't always have to assign to some

kind of variable now i'll leave this one

in here

so i'll leave the console log and then

user

and let's say right above or you know

what let's do it this way so leave the

console log where the user is and then

let's go with another one we'll go with

console.log in this case i'm going to go

with template string and we'll say the

system

system uptime yes and then let's use a

interpolation of course and the method

that i'm looking for

is uptime so again i go with my variable

name and i know i've said this before

but i just want to stress this point

just so we all are on the same page and

in this case i'm going to go with os and

then the method name is uptime

and then let's just add seconds and

again same deal back in the integrated

terminal run node and then app.js and

there it is now of course not only i

have the info i also have the system

uptime and what's interesting this

actually is 100 seconds meaning if i'll

run this notice that you'd expect that

this would probably stop at 60 right

since we have 60 seconds in a minute but

no actually this one goes to a hundred

and then i'm just gonna set up a object

where i'll show you a few more methods

and then we'll move on to a next module

because again the point is not to cover

each and every method the point is just

to give you a general idea how the

modules the built-in modules would work

in node so clear my terminal and then

i'll create a object i'll call this

current

and then os

and then in this object i'll set up

properties and i'll set them equal to

the method

that actually returns that value from my

os module so go with name and os and

this is going to be equal to a type

method then i can get the release

and this one will be equal to os and

then

release again we invoke it then we'll

look for total memory and free memory

total

and mem

and of course i'll go with os and then

total mam as you can see somewhat

predictable and then we're gonna go with

free memory

and it's not going to be surprised if

we're just going to go with free memory

here let's save that one and lastly

let's just cancel log it

and we should

get a bunch of info about our current

operating system again we're going to go

with node and then app.js

and not only have the user information

not only i know

how long the system has been up

in seconds i can also get some useful

data about my operating system and again

we're just scratching the surface of

course there's more methods and

properties but hopefully you have a

clear understanding how powerful these

built-in modules are in node.js since

the node we can interact with the file

system something we couldn't do when we

used our javascript in a browser another

useful module is a path module which

allows us to interact with file paths

easily

and i'm going to remove all my code in

the app.js because behind the scenes i

created a file by the name of

8 os

and module and of course copy and pasted

the contents from the previous video

that's why in app.js i'll remove

everything and the setup is going to be

exactly the same we come up with some

kind of name now most likely it's going

to be path

and then we pass in the module we would

want to get and in this case of course

it is a path module

and then let's just start with a very

useful property

a separator property that returns a

platform specific separator so if i go

straight up with console.log and then

path

sep this is going to return my platform

specific separator so if i write node

mjs

there it is and of course i have forward

slash now if you're using different

platform for you the value might be

different after that let's take a look

at the path dot join so the join method

which joins a sequence of path segments

using that platform specific separator

as the limiter and second thing it does

it returns a normalized resulting path

and in order to show you an example i'll

create a new folder so not a new file

but a new folder i'll zoom in and i'll

say content and inside of this content

folder i'll create another one and i'll

simply call this generic subfolder and

in this subfolder i'll say a test

and text file and instead of the text

file i mean

you can place something you can omit it

doesn't really matter i'll just say text

and then txt and once we save it back in

the app js now i want to use that path

dot join method so i'll say const and

then file path is equal to path dot join

and then we need to pass in those values

as strings so for example since i'm

looking for the content folder

i'll simply say forward slash and then

content then i know that inside of the

content folder i have the subfolder

that's another folder and then

eventually there's going to be a test

txt so we go with test and then dot txt

we save the sucker and then if we'll

cancel log the file path we should

see the whole path and there it is now

of course it is normalized and we get it

as a value so we have content subfolder

test

and txt so if i start adding some type

of forward slashes meaning trailing

slashes then of course they will be

removed we still get the normalized path

and we can also get the base name so for

example i create this file path but i

only would want the last portion of it

how can i access it well

the method name is base name

so we're gonna go with const and base

and path dot base name and we just pass

in that file path and now if we cancel

log the base

we should see the text again these are

just summaries if you want just a

directory of course you can imagine that

there is a method that returns that as

well but since i don't want to cover

each and every method that's why i will

skip that one and there it is now of

course not only i see my normalized path

but i also see the test txt which is my

base and the last method that i would

want to showcase is path.resolve

and why it's so cool because it returns

an absolute path

and once in a while in our applications

we need to provide that absolute path

that's why of course we'll have to use

that method

and when it comes to path.resolve it

accepts a sequence of paths or path

segments and resolves it into an

absolute path so below the base i'm

going to go with cons and then

absolute and that one is equal to path

and we're looking for dot resolve

and here remember when we talked about

the globals one of the first globals i

covered was underscore underscored their

name so this is going to point to this

directory where the app.js is located

and once we're here then of course we

just need to provide rest of the values

in my case that is content

then i'm looking for

sub

folder and then eventually i would want

to get to the test dxd i would want to

get this absolute path and then once i

set up the value of course

if i go with my console.log and if i

provide

absolute

once i run node and objects

you can probably guess that in the

console i'll have my absolute path

to the test txt and if you're wondering

why we would ever want that well

remember our application

is going to run in different

environments right

so of course the path to some kind of

resource is going to be different in my

computer in my local machine than for

example in heroku

hopefully it is clear and now of course

we can take a look at the next useful

built-in module

nice now we know how we can work with

path module and like i mentioned in the

previous video we also have an option of

interacting with a file system

so

what i would want right now is first

create a new file i'll call this nine

and we'll say path

and

module like so js i'll grab everything

that i have in the address

copy and paste

and once we have this one out of the way

i'll just remove

and keep the app.js clean for now

as well as clear the console

and yes we have an option of interacting

with the file system and the module the

name of the module is fs

now essentially there are two flavors

when it comes to file module we can do

it asynchronously non-blocking or we can

do it synchronously which is going to be

blocking but

for time being we'll just cover both of

the setups

and then later in the course

we'll cover what are the differences and

why you should prefer one over the other

one for now just think of them as

different methods but eventually yes

we'll talk about it the whole structure

of the node

and why would you want to use the

non-blocking code instead

as well as different approaches when it

comes to callback functions different

solutions

and for now i just want to show you both

methods essentially four methods

and then we'll just move on to the next

topic

and in order to set this up in this case

i'm just going to structure right away

the methods that i'm looking for and in

the first video we'll take a look at the

synchronous ones so that's why i'll

destructure

read file and sync and that is coming

from require and then the module name is

fs

again please keep in mind it would be

the same thing

if i were to

go like this fs and then fs and whatever

the name

i was going with read file sync and of

course i have access to it i'm just

showing you a different way how we can

access those methods we just destructure

them out of the fs module and then the

second one will be write file sync

write file sync

and then once i have the structured both

of them

then i'm going to set up two variables

so first we'll read two files

we haven't created those files yet but

in a second we will and then eventually

we'll create a new file with write file

sync so i would want you to go to the

content folder if you haven't created

then i suggest creating one

and

i mean i'll keep the subfolder just

because

i believe the path module is still using

it but in a content i'll create a new

file so not in the subfolder but

actually in the content i'll say

first first and then txt

so this by the way sets it up in the

content so let me move it up or i'm

sorry this sets it up in a subfolder i

believe

and it tells me do i want to move yes i

would like to move and now i have the

content

that has the first txt

and then i have the subfolder with

test.dxt of course if you want you can

place it in a subfolder that's really up

to you but in my case i would want them

simply in a content so i'll go the

second one txt and as far as the values

i'll say hello

this is first

first text file

and then of course we can copy and paste

the value and just change it around to

the second file so in the second txt

we'll say second text file

and once we have both of the text files

now let's take a look at how we can read

from the file system

and since we have read file sync we know

it is a method and in that method we

need to provide two parameters we need

to provide a path to that specific file

as well as well what is the encoding so

the node knows how to decode the file

and generally you'll go with utf-8

and we'll first go with first that's my

variable we'll go with

read file sync

my method name and like i said we

provide a path we go to the content

and then inside of the content there's

going to be a first

txt and then as far as the encoding the

default one will be utf-8 but if you

want to be a bit specific just set up

the second parameter and notice these

are all your options and just go with ut

effect okay

and then once we have everything in

place of course we can copy and paste

this is going to be the value for the

second one

and we just need to change the file name

of course

so we have the second one and now in a

console log

we should see both of the text so if i

go with console.log first

and then second

i should have one long text and let's go

with node and app.js and there it is i

have hello this is a first text file and

i also have hello this is the second

text file

and once i have both of them why don't

we create a new file

and the method for that is write file

sync

and the way it works again we provide

two values two arguments one is gonna be

the file name and if the file is not

there

then of course node will create that

file and you'll see that in a second and

the second one is the value that we

would want to pass and i'm going to go

with write file sync

write file sync and like i said first is

going to be a path so you can call this

third you can call this result whatever

you would want in my case i'm going to

go with forward slash content

and then we're looking for result

and then sync and this is going to be

txt and then as far as the value if you

want you can simply pass hello world and

test it in my case i'm going to make it

a bit more interesting where we'll set

up a template string we'll say here is

the result

and why don't we use the interpolation

we'll say first and second

so we'll have first value and then the

second value and you know what when we

add here colon as well so let's say

first

and then let's place a comma

and then we're gonna go with second

again

if the file is not there

then of course

node will create one and if the file is

already there node by default

will overwrite all the values that are

in the file and i'll show you that in a

second so i'm going to go here with node

and app.js and check it out now i have

result

sync txt

and then inside there i have here is the

result hello this is first text file and

also have hello this is second text file

and just to showcase that if there are

some values they will be overwritten by

node

well if i go with simple hello world and

then i run node.js again i have my new

result now if you just want to upend to

the file

well we need to pass in one more

argument notice i have the first one i

have the value that i would like to set

up in a file and the third one is an

object basically an options object and

here the property name is flag and if

you'll set this flag equal to a

then node will append this and the

easiest way for me to show you that is

run node.js and now we should have two

results so we have here is the result

and notice how we're starting a new line

why well because by default we are

overriding everything and then when we

add that flag then of course we create a

new value so these are two very useful

methods that we can use with node to

read files as well as create ones from

the scratch

beautiful and once we have looked at the

synchronous approach like promised i

also would want to show you the

asynchronous and as always let's start

by creating a new file again in my case

that is going to be 10 hyphen and then

i'm going to go with fa

sync and js

and of course i'll grab everything in

the app.js and then just copy and paste

and then back in the app.js i would want

to change these names so i'm not looking

anymore for the read file sync i'm

actually looking for a method by the

name of read file so this is going to be

the asynchronous one and the same goes

with writefile now of course we can

remove all this code as well

and the way the synchronous method works

we need to provide a callback and if

you're familiar with callback

essentially what it means is that we run

that callback when we're done

so

when whatever functionality we're doing

is complete

then we run that callback just like we

normally would do with add event

listener on a button remember we go with

add event listener we add whatever the

event

of course with the button that would be

a click event and then pass in the

callback function and that callback

function will run every time we click on

a button so this is the same thing where

we have the read file function

and we can simply use it since of course

we have the structured then we need to

provide a path so again we go with

forward slash content and then the file

name is first txt and this is where we

provide that second argument and that is

going to be a callback mission now in

that callback function we pass into more

arguments first one is going to be error

if there is one as well as the result

and then inside of the body first i

would want to check if there is an error

and then i can just return null as well

as maybe console.log so we go with if

error and then we'll say return

null or simply return whatever you'd

want and if you want you of course can

cancel log the error as well like so and

then if everything is correct well then

of course i'll have access to my data

which of course has the name the

parameter name of result and since i

would simply want to console log the

result i'm going to go with console.log

and the result but of course keep in

mind that this is where you would set up

the functionality so let's go back and

we're going to go with node app.js

and in this case something really

interesting where we don't get the text

right so we're getting this buffer so

this is what's going to happen where if

we don't provide that utf coding then of

course we'll get the buffer now where do

we add this encoding value well right

here in between in between the content

as well as the path so let's just go

with string and we're looking for the

utf so let's say utf-8

and we'll save that one and let's run it

one more time and of course i have node

app.js and then hello this is the first

text file

and now the million dollar question

well how we can set up the same

functionality

check it out we have read file read file

and then we simply create a new file

with both of these values so if you're

familiar with callbacks

you know that of course we would need to

set up that functionality

inside of this callback where i'm

getting this result

otherwise there's going to be an error

because the only way for me to access

this result

if i'm setting this as a callback is of

course inside of this function and this

is what i was saying before where yes

eventually i'll show you a different

approach because inevitably we'll set up

a callback help and you'll see that in a

second so what i would want to do right

now when i get back

my first text file well now of course i

would want to assign it to some kind of

variable

and then i would want to read that

second file right and then eventually

once i read the second file then of

course i would want to create that new

file

and the way it's going to look like

i'm going to go with const and i'll say

first

and you can name it first text i'm just

going to know it first and this will be

equal to my result okay awesome and then

right after that result again i'm going

to go with read file

and then the same thing

we provide a path so we go with content

and then in this case of course we're

looking for second and then txt then we

need to provide the encoding so node

knows how to decode that and we go with

utf-8 and then of course we need to

provide our callback again same deal we

go with error

and result and in order to speed this up

i will copy and paste so just grab

everything starting with if and ending

with the result copy and paste again

this is the case where we're checking

for the error first if there is an error

we cancel log it and if everything is

successful we assign this one to the

second one and then eventually now i

would want to set up my right file so

again it is a function

we need to provide that value and we

already have result sync txt that's why

i'll create a new one and i'll call this

result and async so again we're looking

for the content then we go with the

filename which is going to be result and

a sync

and txt of course since there is no file

node will create that for us i'll right

away set up my data now if you want of

course you can copy and paste this

functionality this is totally up to you

where basically we use two of them and

in my case this is exactly what i'm

going to do in order to speed this up if

you want to create something from

scratch of course that is also an option

and i'm just going to copy and paste

that's my template string and again if

you want to add this flag

you can definitely do so in my case i'm

just going to omit that so here's the

result i have

first and second

and the reason why i have access to them

because of course i'm looking

in the outside scope of this callback

function and then again we have a

callback function in the right file i

know there's tons of callback functions

that's why we'll have to set up a better

setup when we're handling these

callbacks but we'll do that a little bit

later so for now let's just add a

comment here where we have first

parameter second parameter and then

third parameter and of course this is

going to be again our callback where we

have error

and result

and then inside of this callback finally

we can take a look at the value and of

course the value will be in this result

now of course we're creating the file

and all that but hopefully you get the

gist that if you'd be doing something

where you're looking for this result of

course it would be over here so again

let's check for error quickly if there

is an error then of course i would want

to return

as well as console log the error

just in case and if everything is

correct let me just console log the

result so save it here

and

two things we need to watch out for

maybe there's an error and second one we

should create a new file by the name

result and then async txt let me clear

the console and we're going to run node

app.js and i do get an error and error

simply tells me that i did not add the

dot in front of the content so i would

need to go back to write file and just

add that and once we add the dot we are

going to be in good place where i'll

clear the console and i'll run one more

time node app.js and then the result

will be undefined okay that's fine like

i said in this case we're not expecting

anything back but what's really cool

that in the result async we should have

our text here is the result hello this

is first text and then the second text

so hopefully it is clear

this is how we would use the async

pattern so let me zoom out right now

here and you'll see this

famous callback hell and in the next

video i would want to give you a

brief description of what are the

differences between the asynchronous

approach or non-blocking approach and

the blocking one the synchronous one as

well as what are the alternatives to

this callback l all right and just to

give you an early taste of the

differences between the asynchronous or

non-blocking and synchronous which is a

blocking code why don't we set up few

console logs now before we do that i

will create a new file

and i'll say 11 here and by the way i

definitely need to zoom in

just so you don't think that i'm

cheating fs

and async js

and let's go to the address we'll select

everything and copy and paste and of

course in next video we'll set up

different module in this appdress so for

time being i can just remove it

and then like i promised we'll set up

some console logs so why don't we go

back to fs and by the way during this

video i'll zoom out because i definitely

wanna go back to this

evil evil callback hell that we're

getting from nesting callback within the

callback and as far as fa sync

let me zoom in

and why don't we set up a console log in

few places

let's say before we're accessing the

file

so i'm gonna go with log and we'll say

start

then we're gonna go with write file sync

and then right after that we're gonna

say i'm done with the task and then

inside there let's write done with this

task copy and paste

and we're gonna go with starting the

next one

starting

the next one

meaning the next task

so that should do it and of course i

need to go with clear so clear my

console and i'm gonna go to node and

then the file name is 10

iphone and then fs and we're looking for

sync

i run it and notice something

interesting where i have the start

so that is going to be before i read the

files and only then once i'm done

writing that file

i have done with this task and starting

a next one

and what we need to imagine that of

course this task

of getting those files as well as the

second one of setting up that file well

it might be very time consuming right

and imagine that if we have even 10

users and they're all the time using our

application

and if for example this one user does

this one task or both of them

and they take really long time what

means that

node is not going to be able to serve

other users and trust me it is at the

end of the really really big deal and

notice how javascript is reading this

code synchronously

it just goes line by line so we start

with this task then we read these files

and then we write the result and again

if this is something that takes really

long time then pretty much your

application is down

so no other user can do anything with

that application because one of the

users is for example reading these two

files and then writing one again this is

a very simple example but you need to

picture that of course there's going to

be tasks that take longer time

and as an alternative let's take a look

at the async approach

so here again we'll set up some simple

console logs and again we'll cover this

in a bigger detail a bit later for time

being let's just set up console logs and

you'll see the biggest difference

where i'm gonna go with log

and let's say start so i'm gonna do that

before i read this file

and then i would want to go inside of

the right file

the last one and instead of console

logging result which of course is

undefined since in this case we are not

getting anything back now i want to go

with done

with this

task and then right after my first read

file i'm going to go with log

and starting

next task

hopefully you're able to follow along

again before the read file inside of the

right file and then right after the

first read file because of course the

other ones are nested inside of this

callback and then if we go to node and

if we just change it around to 11

and then fa and i believe it was async

and if we run it

notice something cool

where i have my start

and then i right away have this starting

next task

and eventually i have this done with

this task so what this means

is that since we have this asynchronous

approach the moment we start this task

we just offload

we just offload this task and we

continue with our code so that way when

user number one for example comes here

and wants to get this functionality

yeah sure here node just offload this

task and then your application can keep

on serving other users again

it seems a bit trivial at the moment

because we have a basic approach but

hopefully you get an idea where in one

case we have everything happening line

by line so only when we're done with the

task we're starting a next one

and with this approach we start a task

and we just offload that task and then

we start a next task right away and

eventually yes we have done with this

task in the console as well

now as far as the implementation as far

as the callbacks

yes this is a bit messy right notice how

we only want to accomplish few tasks and

it's already somewhat off a pain now

alternatives are using promises

as well as async await now again

hopefully you understand that when we

talk about reading the file as well as

the writing or file

i use this as an example of some kind of

task that would take a long time now for

the remainder of the course mostly it's

going to be reading from the database

writing to the database and that sort of

thing but this is a very good

illustration of how some tasks would

take some time so of course we would

need to use a callback and as far as the

callbacks yes you can use them but the

code is going to get messy somewhat

quickly that's why a bit later in the

course we'll take a look at the

alternatives which are promises

and a sync await and i have to tell you

honestly for the remainder of the course

we'll use async await because in my

opinion it is just easier to work with

excellent and up next we have http

module

but before we continue let me just

mention that i purposely won't spend too

much time on explaining every single

http method we're going to use in great

detail and here's why

you see starting from next section

all of our work meaning code in some

shape or form

will revolve around server setup

aka http module so that point of course

i will cover every last bit of syntax in

great detail

at this point though i think it's just a

waste of our time so if you're confused

about something http related

don't sweat it we will return to that

subject shortly and cover it in far

greater detail

now if you're wondering

why we bother with http module at this

point at all

since we're going to use it later anyway

you see with the help of http module

i believe i can show you some core

features of node in action

and give you somewhat of a

visual representation of them otherwise

i would have to base everything on

slides and i don't think it's the best

approach

so long story short

if you're iffy about something http

related

just please be patient and i'll answer

all your questions

in the next course section

nice i think we've got a good initial

understanding of how the

file system module works in node and

hopefully i did not lose too many of you

so hopefully there are still some

students left in the course because i

fully understand that seeing this for

the first time

is probably a bit overwhelming

and what i would want to do next is

cover the last initial module the

built-in module and that is going to be

the http module which is going to allow

us to

set up a web server now please keep in

mind one thing we'll just cover the

basics because the large part of this

course is going to be creating your own

server and setting up the api now

granted we will use an abstraction on

top of the http module and that is going

to be the package by the name of express

but the whole point is going to be

exactly the same that's why again we're

not going to cover everything

in greatest detail at the moment because

i don't see the point of repeating

myself

and now i want to go back to objects

i'll zoom back in

just so you can see better what is

happening by the way let me check my

zoom level so i'm going with settings

and i think that should do it my zoom

level is two at the moment and then back

in the app.js

let's grab the http module and we'll

assign it to some kind of variable as

always

let's go with require and we're looking

for http that's the module name and the

method we would want to use is create

server again we'll assign this to some

kind of variable and in this case the

variable name will be server then we go

with http

create server and this create server

method is looking for the callback and

in that callback function

we have two parameters and both of those

parameters are objects and since they're

parameters you can call it whatever you

would want but a common practice is

calling them rec and res now this first

parameter represents the incoming

request so imagine a client is

requesting from the web browser your

webpage so you'll have information about

the method and all kinds of useful stuff

in that request object and the response

is what we're sending back

now we're not done of course we'll set

up more code here but before we do

anything we also would need to

specifically say what port our server is

going to be listening to and that's why

we'll go with server

and listen so that's another method and

again this is arbitrary but i'm gonna go

with 5000. again

if this looks like a lot of gibberish

where we have the request response as

well as the ports don't worry

later in the course i'll cover that in

more detail as well as show you some

useful slides and all that good stuff

and as far as the response well

we have few methods we have write so we

go with arrest and again this is the

object and notice here how i'm not using

the rack yet so i'm not checking for

anything i'm just concerned about my

response and the method name is right

and inside the right we just come up

with some kind of text and i'll say

welcome

to

our homepage

homepage and once we have sent back the

response i also would wanna end my

request so i'm gonna go with res.end

and once we're done setting up the code

inside of the callback function now of

course i would want to open up my

terminal

clear everything and we would need to

spin the sucker up and of course the way

we do that is node and then objects

since that is the file name make sure

that you save it though so before i run

i'll save it and then notice something

interesting notice how we're not exiting

so previously every time we ran the file

every time we ran node and then whatever

the file name we exited from the file

right so node was done executing the

code and we just moved on now in this

case since we have a web server what do

web servers do

they keep on listening for requests and

actually you want your server to always

be up and of course if i go to my web

browser

and then

i'll make this bigger

and if we go with localhost

and of course in this case we have 5000

there it is we have welcome to our

homepage so now of course we have

effectively created our first website

now granted it's very basic but at least

we have something on screen

and before we discuss the external

modules

and actually set up a module that nicely

watches our code and does the restarts

for us

i also want to showcase what we have in

the request object now this is going to

be a giant object

so i'm not going to cover

each and every property however i would

want to showcase a property that gets us

the url and what would be the url well

that would be an address and if you're

worked with reactor or dom you know that

for example for the homepage we used

forward slash and then if the client

wants to go to for example about page he

or she would enter forward slash and

then the about now in our case notice

how we're still serving the same content

so just to give you a quick introduction

of the request object as well as set up

a bit more realistic application we're

going to go with the request now again

if you want you can log it so we're

going to go here with request and you'll

see that it is a giant object now since

we made some changes we do need to stop

it and then we'll go with node object

but notice how we're not right away

console logging the request object why

well because server

is waiting for those requests so we need

to go back to our browser and then

refresh and then of course once we

navigate back like i said this is going

to be a

giant object which bunch of useful info

now what we're looking for

is the url property because that url

property is going to tell us well what

address client is requesting so what

endpoint the client is requesting and

like i said for the home page the common

practice is using simple forward slash

so in here we can set up the if

statement where i say if request url is

equal to the home page then of course

this is what i would like to send back

and just to speed this up i can tell you

that we can cheat a little bit where we

can just place everything in the end

and in my case i'll just cut out my

string so we have res dot end so now we

simply send the text

and now of course i also would want to

check for the about or contact or

whatever so in here let's go with if

and then request

and url and if that one is equal to

about

about then of course i can send

different text and as far as the text

i'm just going to say here is

our short

history and then lastly well what

happens if the user is trying to access

a resource that doesn't exist

on our server

so we'll have the about page we'll have

the home page what about if the user is

asking for a contact page that we don't

have well here we'll simply set up a

default response we'll say res that end

and just to make it interesting i'll set

up the template string and i'll show you

that if we really want to we can also

pass indirectly html and i'll say oops

an explanation point i'll close my html

again please understand this is just a

basic scenario of course that's not how

we'll be setting up our apis or nothing

like that but just to give you a quick

intro

we'll do it quick and dirty where

there's going to be a paragraph and

we'll say we can't

seem to find the page

that you're looking for page

you are looking for

looking for and at the very end i would

want to set up a link

that allows the user to navigate back so

go with href and i'll say forward slash

which just means home page and we're

gonna go back home

let's close our link let's save that one

so at the moment of course we have the

about and by the way

almost forgot

yes we do need to stop the server and we

need to go with node and then app.js

refresh one more time there it is notice

how we don't have the about we can't

seem to have the page you're looking for

and that is actually a bit interesting

because it should be available right and

of course the reason is because i messed

up on the url property my bad let me do

this one more time

and we'll stop the server here

again let's run node app.js and now we

should have here's our short history

that's our about page then we have the

homepage and of course you already

familiar with our error page so if i'll

go with error or any kind of resource

that doesn't exist

then of course we'll get the error page

and of course we can bravely navigate

back home and we go back to our home

page that should do it for the quick

intro of base modules

and now of course we are ready to move

on to our next topic all right at this

point we're familiar with two types of

modules

our own

as well as the nodes built-in ones

but

just like in any good infomercial

i'll say but wait there's more

we also have access to the world's

biggest code store

and before you seriously start

questioning my mental state

imagine this scenario

you're building an app

and of course as any good app it needs

to have a slider

just for funsies

now at this point you generally have two

options

build it from the scratch yourself

or search on google and copy paste

someone else's solution

well have no issues with either of these

options keep in mind that someone

somewhere

has struggled with the same issue the

need for the slider

and there's a good chance that that

person

was kind enough to build it

and share

the whole project with us

so our only job

is to go through the docs

and with the help of one command

just add it to our project

we can do that because when we install

node

we automatically also install npm

or node package manager

and npm enables us to do three things

reuse our own code

in other projects

use code written by other developers

and lastly share our own solutions

with other developers as well

the npm project is hosted at

npmjs.com again the site is

npm.js

and here you can find everything

starting with useful utility functions

to full-blown frameworks and libraries

and as an example if you're familiar

with react you know that react has the

create react app package

and of course it is hosted on the npm

a typical node project

will have more than few npm packages

installed as dependencies

and before we install some cool packages

let's talk about naming

npm calls the reusable code a package

and a package essentially is a folder

that contains a javascript code

now another names you'll hear

are modules

and dependencies and honestly at this

point

all three are used interchangeably when

talking about shareable javascript code

so don't be surprised if during the

course i call them any of these names

package dependency or module at the end

of the day they all mean the same thing

lastly let me just mention two things

first

there is no quality control in npm

registry

anyone can publish anything

so it's up to you to sniff out the empty

and useless packages and yes there are

quite a few of those ones out there as

well a good indication of the security

and usefulness of package is the amount

of weekly download if the number is high

meaning if it's popular it's a good

chance that it's a battle tested and

ready to go

and that brings me to my second point

remember the slider example we discussed

in the beginning of the video

when it comes to npm packages there's a

good chance that if there is a bug

someone else has already fixed it

and as a result it's already fixed in

the package

or

there's a working solution

all right

so that you did for intro let's start

using node package manager

in our own project and as a side note if

you want to search for some packages

just visit

npmjs.com

and then for example if you're looking

for the bootstrap you'll find the

package

and of course you can click on any of

them

this will bring you to the docs as well

as weekly downloads and rest of the

stuff once we're familiar with node

package manager let's see how we can

start using it in our own project

and the good news is that it's much

simpler than you would expect you see

when we install node we also install npm

and because of that we have access to

npm global command

and you can check the npm version by

running npm

version in your terminal just keep in

mind that the version most likely won't

be the same as your node version and

that is totally okay so you can either

do that in the terminal

or of course in the integrated terminal

and you can simply type npm and then

hyphen hyphen version i believe you can

also check by hyphen hyphen v and there

it is of course now we have the version

for our node package manager and then we

have two flavors we can install package

as a local dependency and that just

means that we'll only use that package

in this particular project that we're

working on and the command for that one

would be npm

install or i for short and then whatever

is the package name so whether that is

bootstrap low dash express or whatever

or we can install dependency as a global

dependency and that just means that we

can use it in any project and the

command for that one would be again npm

i or install whichever method you prefer

and then hyphen g so this is going to be

the flag and then again the package name

now when you install something globally

most likely on a mac they will ask you

for the sudo so you'll have to provide

the credentials that's why you'll run

sudo

npm

install and then hyphen g and again

package name

as far as which one you'll use more

often that definitely will be a local

dependency flavor

because even though yes you can install

packages globally with arrival of npx

there's actually less and less need for

setting up something globally that's why

we'll focus on local dependencies first

how to set it up in our project and then

in a few videos when we talk about npx

i'll cover why there's less need for

setting up something globally now

there's one more thing that we would

need to set up in our project as far as

dependencies so i know i know you're

eager to start installing the packages

but

let's just wait a little bit and next

video we'll add that extra thing that

we're missing right now and then we'll

be in good shape and then we'll start

installing every package under the sun

excellent we now know that we have

access to the npm global command we now

know that in order to install the local

package we will need to run npm i

and the package name so what are we

missing well we're missing file by the

name of package.json

and essentially you can think of it as a

manifest file that stores important

information about our project

and there are three ways how you can

create package.json first is the manual

approach where you just create a

package.json in the root and please do

that in the root if that's something

that eventually you decide doing

and then of course you would need to

create each property or

there are two

ways how we can automate this and the

first one is running npm init

and in there they'll just step by step

ask you the questions and if you want to

skip it you can just press enter

and the another way the third way is

running npm init with a y flag and then

everything is set up as default so i'm

not going to show you the manual

approach it's just too time consuming

and we'll right away go with npm in it

first i'll show you the step by step

approach and then of course i'll show

you how everything is set up by default

using the y flag so go to your terminal

and just type npm in it and there it is

of course now they tell you that there's

going to be a walkthrough of creating a

package.json file and the first one is

the package name and by default of

course it is going to use the folder

name now keep in mind that if you

eventually want to publish this package

then the name has to be unique so you

need to make sure that

nowhere in the npm

you can see the package with the same

name and i'm just gonna go with tutorial

as far as version we'll talk about

versions shortly so i'll just skip this

one as far as description whatever again

is just the default now as far as the

entry point eventually will change it

but for now it's good enough we're going

to go with one intro js and then the

test command as well as git repository

and keywords and author and license and

we simply say yes and we are in good

shape so now of course we have the

package json file with name version

description as well as the main property

and of course the scripts author and the

license now i'll remove it

i'll say delete and i'll show you that

of course you can skip all those

questions by simply typing npm

in it and why

and as you can guess

yes of course you can come here later

and then just change these values that's

why it's definitely faster to just type

npm

in it and then the y flag

so why do we need this package.json well

because if i would want to install the

package the local package

now of course this package is going to

be stored as a dependency and to show

you that let's just go with npm and you

know what

let me clear the console first so we're

going to go with npm

i

and then we're going to go with the

package name lowdash and if you're not

familiar with lodash it's just a utility

library and i'm just specifically using

for installation purposes there's no

real reason to have low dash for our own

project but it's just something pretty

interesting that i would want to

showcase that's why we're using lodash

and we run it and notice how we

installed the package and check it out

now in the package.json we have

dependencies property and it's an object

and inside of that object we have a

package by the name of lowdash now i'll

show you

in this video or maybe in the next one

why it's so important to have this

package.json

but another thing that i would want to

showcase once we can see that we have

dependencies property if you go in your

visual studio code

and if you click on refresh explorer

what you'll also notice

is this node modules folder and in that

node modules folder this is where all

the dependencies

are stored

so if you don't have that folder already

and pm creates it so in our case of

course we didn't have any dependencies

so when we install that first dependency

npm creates that folder and this is

where you'll find the dependencies now

notice something interesting where for

the low dash

we only have one folder right so we have

only one dependency

but when we need to keep in mind that of

course there's going to be some packages

that have other dependencies

and that's why i first installed lodash

just to showcase that yes once you

install dependency of course it is going

to be in node modules but if you'll try

to install a package that is bigger that

uses other dependencies you'll notice

something pretty cool where if i clear

my terminal and if i'm gonna run npm i

and then bootstrap again you can use any

other package you'd want this is just to

showcase how the packages work we won't

use the bootstrap in this project so

once i install and once i refresh

check it out not only i have low dash

not only i have bootstrap which i

installed but since bootstrap is using

jquery as well as the proper js now

these are installed as dependencies and

if you take a look at the dependencies

property now of course we have the

bootstrap as well and again

the whole point of this video is to

showcase why we need package.json

so we need it because we need to provide

information about our project and inside

there

a very important property is the

dependencies one because in there we'll

just store the dependencies which our

project is using and then some packages

are actually going to use

more dependencies and they will be

automatically installed as well in our

case that was bootstrap and

just to give you a taste of the package

why don't we just navigate to app

and i'm going to do that below the

comments of course you probably would

need to clean the file and as a side

note the last module the http i saved in

file by the name of 12 http

and back in the app.js in order to start

using

the module

in our case i guess i'm gonna go with

low dash

first i would need to set up the

variable and common convention is

calling the variable like so and we'll

set it equal to require and now of

course we have access to the low dash

now this is the difference between

node packages

like for example the http

or the file module or whatever and the

ones that you install the external ones

the external ones you always have to

install first

if you won't install the dependency well

node won't be able to find it so in our

case we did install the dependency the

lowdash so now of course i can just

assign it to the variable and since

lowdash is utility library why don't we

test out one of their methods and i'm

just going to go with items and i'll

create an array of arrays so items is

going to be an array however

the items are going to be arrays itself

so two and three

and then we're gonna go with four

and low dash has this method the flat

and deep method that effectively will

just spit this back as a flat array

and the way we set it up we just go with

const and i'll call this

new items and then since we have access

to everything

in this variable now i can simply go

with underscore here dot and then flat

and deep so flatten deep and then we'll

pass in the items and now if we console

log

new items and if i go to my terminal and

just type node app.js and by the way i

need to save it

so let me go back i'll say node app.js

and once we run check it out in a

console i can see of course the one two

three four so lowdash has the method by

the name of flattendeep we have access

to it because we install it as

dependency and now of course i can start

using it now we're not gonna use

bootstrap in this project because that

would be too time-consuming bootstrap

was just used so you can see that some

dependencies will have

more packages so once we install one

dependency there's actually going to be

more dependencies and hopefully you have

a clear understanding of how you would

set up package.json how we would install

the package and next video i would want

to showcase why having package.json

is so crucial and so beneficial

when we are starting to share our

project with other developers

awesome we have package.json we

installed few dependencies

and now i want to cover

why having package.json is so crucial

when we start sharing our project with

other developers and for this example

i'm going to use github as well as few

basic git commands and my assumption is

that since this is somewhat of a

advanced course you're already familiar

with git and github and you have the

account if you don't please stop the

video create the account

and just use your favorite search engine

to learn about the basics of setting up

the github repository as well as basic

git commands so

our task is to push this up to the up

and now million dollar question are we

just pushing

everything up including the mode modules

which

for the most projects is going to be

somewhat big

i believe i just checked in our case it

was like nine megabytes but trust me it

always gets way bigger than that

or

we would just want to send the code and

you can probably already guess that

since i'm implying that the size is too

big that we'll have to push this up to

the github without the node modules and

we'll start by creating a dummy repo on

a github

so let me open up a new window

i'm going to go with github

and i'll just create a temp repo

and then i'm just going to create a repo

and i'm looking for these three commands

essentially i would want to get that url

the remote url so i know where to push

it and then inside of the repo before we

set it up as github repo first i would

want to go with new file and we'll

create a git ignored because of course

what i would want is to place

the node modules

in a git ignore file because that way

they will be ignored by my source

control and i won't be pushing up this

giant folder to the github because

you'll see in a second that there is no

need for it so we're going to go with

forward slash and then node modules and

if you're not familiar with git ignored

it's just a file

that specifies which files are going to

be ignored by the source control and in

our case as you can see i'm placing node

modules inside there then i'll clear my

console and i'll just initialize this as

an empty git repo and then we'll add

everything so git add git commit

we'll just say first commit

first commit and then i'll copy and

paste those three commands in order to

set up that url

the remote url and once i have this in

place

should be able to go back to my github

and there it is this is my repo

now probably your next question is okay

so we pushed it up to the github

but i can clearly see that in my app.js

well technically i'm using the load as

dependency right

but we didn't push up the node modules

folder so how the person who is going to

get this repo will be able to run the

code in the app.js

since there's no node modules and you

told us previously that we can only run

it if the dependency is there well let's

check it out i'm going to go with clone

option so i'll just get the

url i'll navigate back here

and i'll do that in messed up again it

doesn't really matter

we're just going to go with desktop and

then git clone

now i copy and paste the url i'll open

up a

new instance of my text error copy and

paste and this is where the magic

happens

if we have package json we simply need

to run

npm

install

and what is going to happen

the npm

will check

for dependencies that we have in the

package.json and automatically set up

that node modules folder so if i go here

first of all i can see that there has

been some changes that is already good

news that just means that

i have my node modules and if i refresh

check it out so now of course i have my

node modules folder and if you have been

using react applications you're probably

already familiar with this one where

again

when you are setting up the code

you're not sharing the node modules

folder and i can showcase that by taking

a look at my react projects and that's

not what i wanted i didn't want to look

at my awesome picture what i wanted is

react

and then let's go with project

and you'll see that in that repo

we have bunch and bunch of folders and

each folder has two more folders final

and setup and now check it out

none of them have the node models

because imagine the size

of this sucker if i would push

for every project for every folder the

node modules instead i have package json

so when you get the repo when you clone

the repo or download or whatever

then of course you get the package json

and in here

these are the dependencies and you just

run npm install and they are being

installed okay hopefully it is clear

that why it is so crucial to have the

package.json because we can just share

the code without dragging the massive

node modules folder with us

we can simply just provide what packages

our project is using

and then once we get the repo then we

just run npm install that is the command

and then npm will install all the

packages that are in the dependencies

awesome we're familiar with

npm we're familiar with package.json

now let's finally install the dependency

that we'll use for the remainder of the

course and that is no other than the

node one and of course if you want to

get more info you can visit the npm and

you can search for the package but as

far as the general setup

is just to watch our files

and then restart our app for us so that

way we don't have to each and every time

type node and then whatever the file

name

and we can install it as a simple

dependency that is definitely an option

but since i also would want to cover

depth dependencies we'll install that as

a depth dependency and the command for

dev dependencies is following where we

go with npm and then i or install

whatever and then we go with nodemon so

that is the package name and then you

can either do hyphen d

so that just signals that that is a that

dependency or you'll see this save and

dev so again whichever method you choose

that is really up to you but just

remember that both of them will save it

as a dev dependency so let's install it

and then i'll talk about it why we would

want to set up as a div dependency and

the reason for that is because if we

think about it do we really need nodemon

in production

and the answer is no when we push it up

to digitalocean or heroku or whatever

we'll of course use something more

serious than nodemon to restart our

application

pm2 comes to mind but while we're

developing yeah that is an option

so in this case we'll add right away

nodemon to the dev dependencies now what

else what kind of packages we would add

to dev dependencies

for example testing packages for example

linting for example formatting and that

sort of thing again nothing stops you

from jamming this in dependencies

but

if you think about it it makes way more

sense if we add this as dev dependency

so we use it while we are creating the

app but then once it's in production

then we just share the dependencies that

actually the app is using

not the ones that we used while we

developed the app hopefully that is

clear

and once we have the package we're

almost there now we just need to

understand how the scripts

work in a package.json and at the moment

as you can see we have the test one we

won't use that one and inside of the

script object we just set up the

commands and as a side note

we can set up the command right now even

without the node mod for example i could

go with start and that command will be

equal to npm

and or i'm sorry node and then for

example app.js so that is my command and

once i save my package.json instead of

running this node app.js i can simply

run npm and start and there it is as you

can see

same functionality i run app.js and i

get back the array as well as the hello

world again we still exit the

application so it's not like we're out

of the woods but i'm just showcasing

that yes we can set up the commands and

then in the command we just provide a

value and in this case of course it is

node and app.js

now for some commands you can simply

type npm start as you can see but for

some of them you'll have to provide the

full value and that is going to be npm

run and nor to showcase that i'm going

to go with dev and that one will be

equal and here we're gonna go with a

node

mod and then app.js so instead of

running node

like we're doing in the start now i'm

setting up a dev command and in order to

run this one i'll have to go with

run and then whatever here's the command

name again some of them you'll be able

to use the shortcut where you go with

start and some of them you'll have to go

the full route with npm run and then

whatever is the command and as a side

note yes you can still run npm run start

and this is also going to invoke the

command but

in our case we have dev and in here i

have

nodemon

and then app js

so let's try it out let's say first the

package json and you should notice

something pretty cool where if i go with

npm

run and dev

now i'm spinning up the node one

and it tells me that nodemon is watching

my application

and since i know that of course we can

test it out where i'm gonna go with

console.log

and then instead of the hello world

which i have after new items i'm gonna

go with hello people and you should see

something interesting where once i

change the text yep nodemon restarts

my app and now of course my value is

hello people awesome so now i don't have

to type every time the node and then

whatever file name nodemon automatically

just restarts my app and i simply set it

up as a script now if you want to change

this around if you don't want to run npm

around dev you can simply say nodemon

and then app.js and just remove the dev1

completely and a side note again if you

have worked with react project you are

familiar with the setup because for

react again we run npm start and then

there's a value that spins up the whole

react dev server where we can see our

application not bad not bad well we're

still on a roll let's cover how we can

uninstall the package as well and as a

side note if you want to stop the

nodemon just press again ctrl and c

and notice how we're of course stopping

the nodemon and again if we want to spin

up we'll just go with npm start and as

far as

uninstalling the package we have the

command for that and the name is

uninstall so i'll stop the nodemon and

in the terminal i'll type npm

uninstall and then of course the package

name which in my case is going to be a

bootstrap now this is one of the

approaches how we can do that and

there's also a nuclear approach now why

i'm calling this a nuclear approach

because that way we remove the whole

node modules folder and don't worry

once you run the npm install then of

course you set everything back up from

the scratch as well as you would remove

this package like json and don't worry i

will cover the package.json file a bit

later

and the way that is going to look like

well we can first clear the terminal

i'll install the bootstrap from the

scratch again so say bootstrap here and

by the way

probably need to add npm i

and now again as you can see i have it

as my dependency and then like i said

the nuclear approach is removing the

node modules yep

and then removing the package log

and then just running npm install now of

course in the package.json if i want to

remove the bootstrap for example in this

case i can simply remove it from my

dependencies so i just remove it in the

package.json then clear everything

and then we go with npm and then install

and now we'll get from the scratch the

node modules

since we're the ones who removed it

and also we'll get that package hyphen

lock json now i'm showing you that

nuclear approach because if you have

used gatsby you know that cats be

somewhat notorious for sometimes just

being a little bit annoying where you do

need to remove the cache folder you do

need to remove the node modules as well

as package lock and then once you start

up everything from scratch

then

as a magic the gatsby app starts working

and check it out if we take a look at

the node modules now yes there's a bunch

of modules that nodemon is using right

but there's no bootstrap and i can

clearly see that because there's nothing

under the letter of b so we can clearly

see that we removed bootstrap from our

dependencies

all right and now let's take a look at

how we can install package globally and

what would be some of the use cases and

first let's start with command let's jog

our memory command was npm install and

then dash g

and the package name and in mac they

might ask you for permissions so you'll

have to start with sudo and then again

same spiel npm install blah blah blah

and first i want to showcase that i

haven't installed

nodemon globally

and the easiest way for me to showcase

that is by running nodemon and app js so

we'll try to install

nodeman package globally why well

because then i can use nodemon in any of

my projects at the moment i have it as a

local package and of course i can spin

it up by running npm start but let's

imagine scenario where i have i don't

know 20 nodal applications and i'm

constantly working on node applications

so to make my life easier i will install

node 1 globally and then i won't get

this error because at the moment you can

see command not found normal all right

so how do we do that well we can install

it

in our terminal or we can do it in the

integrated thermal it doesn't really

matter when it comes to global packages

you can install it from anywhere so in

my case i'm just going to navigate back

to my terminal just so you don't think

that i'm cheating

and i'll zoom in and we'll simply run

and by the way i need to start with sudo

and then npm install

and hyphen g and of course we're looking

for nodemon so now of course

i'm prompted

to enter my password and once i enter my

password

of course i'm going to install nodemon

globally and now

in any of my projects i can simply go

with command of nodemon and then

whatever

is the file name now

to show you some of the use cases if you

work with gatsby you know that they have

the global gatsby cli tool and that was

one of the reasons why you installed

something globally is because well you

used one of the frameworks for example

react or gatsby in this case and then of

course in order to set up the gatsby

project or

react project you needed to install this

globally now things have changed though

with arrival of npx and i'll talk about

the npx at the end of the video but

notice if you navigate to your react

docs and if you look for create react

app which again

was something that you needed to install

globally

now they suggest this npx route where

essentially you go with npx and then

again whatever is the command name for

example for create react app that would

be create react app for strappy the

headless cms that would be create

strappy app and hopefully you get the

gist where for every resource that of

course would be different and with that

command you don't have to install that

tool globally

for example again in our case we're

installing nodemon but normally prior to

npx you would install this create react

app globally and then you can spin up

those react projects now i'm going to go

back to my terminal as you can see i was

successful so what's going to happen if

i go back to my project and if i run

nodemon and app.js since i have

installed that package globally

there it is i spin up my app.js and if

you don't believe me i can change it

back to hello world and i have no issues

hello world and there it is now of

course i have hello world e in the

console so hopefully it is clear that

yes we can install packages globally and

yes one of the biggest use cases was

working with some type of front-end

library

but with an arrival of npx

things have shifted where now those

libraries suggest using the npx route

instead as far as my personal preference

since i'm recording a lot of courses and

since some of the global packages

usually introduce some kind of bugs

to the students now not for all the

students but there's always this one

student who just has a lot of issues

with the global package

personally i avoid them as much as

possible so i always either use the mpx

or i just set it up as a local

dependency again it's not a rule you can

do whatever you would want but i'm just

telling you what is my preferred option

as far as what is npx it stands for

execute and official name is the package

runner it is a feature that was

introduced in npm

5.2

and again the main idea is following

where you can run that cli tool for

example in this case create react app

without installing these globally so as

long as you have npm with a version of

5.2 or greater instead of doing this

whole spiel of setting up the cli tool

globally you just go with npx and then

whatever here is the tool name and of

course the last one is the folder name

as far as the package log json

why do we need it well if we take a look

at our dependencies we can see that they

have versions

and if you remember

some of the dependencies have

dependencies on their own and of course

we need to keep in mind that those

dependencies have versions as well

and for example the person who gets your

project you probably want them to have

the same exact setup because keep in

mind

as these versions change

well so does some of the functionality

correct so for example you set up to

your whole project you use some kind of

dependency that uses some other package

and that version changes not for example

for the bootstrap but for the jquery and

then pretty much your project

is obsolete meaning

it might get some bugs because the

version of the jquery changed so that's

why you have this package.json

and in there you have those specific

versions for all the packages

not only for dependencies but also for

the packages

that the dependency is using now as far

as this version we have three values and

you can think of it as a contract

between us

the people who are using the package and

the person who is creating and first

number is a major change so when this

changes that means that there are some

breaking changes now the second one is a

minor one so that means that it is

backward compatible so for example if

this changes to 18

i shouldn't expect any breaking changes

and the last one is just a patch for the

bug fix so that's also something to keep

in mind when you decide to publish your

own package that of course that's why we

have here this version now lastly i

would just want to mention that if

you're interested in more info about the

package.json i would suggest this

resource

so i simply went with package.json then

keep on scrolling keep on scrolling and

you're looking for i guess this blog

post right so the name is the basics of

package.json and in here you literally

find everything explained to the

smallest detail whether that is a name

version and rest of the fields that you

can find in a package.json beautiful we

now know how to utilize npm and for

starters as a result for the remainder

of the course instead of frantically

typing

node.js in a terminal we'll simply spin

up nodemon and it will watch for the

changes and restart the app for us

now what before we move on to creating

servers with express.js there are a few

important node topics i would like to

cover first and those topics are

following event loop async patterns in

node.js events emitter and streams in

node.js while these topics are extremely

important please keep in mind that our

goal is to only understand the general

ideas behind these concepts

and i only introduce them so you have an

overall understanding of how things work

in node.js before we build our first

node.js app

if you're not satisfied with my

explanations or simply want to do more

research by yourself just type any of

these terms in your favorite search

engine and i can guarantee you'll find

plenty of useful resources within a

matter of seconds

like blog posts youtube videos and

conference talks with that said it's my

strong opinion that it might be easier

to understand those concepts more deeply

so not just a general understanding but

understanding them more deeply once you

have one or few working node apps under

your developer's belt let me also

mention that in order not to waste your

time with time consuming setup

in few upcoming videos i will run some

pre-built code

let me be very clear though i'm only

going to do that in a few videos

and for the remainder of the course we

will type out everything together

all right

and let's kick things off by discussing

the event loop

now event loop in node.js is one of

those topics where i could spend the

entire course discussing it and it still

wouldn't be enough so let's try to avoid

that and instead just understand the

journal concepts

while there are tons of useful event

loop explanations out there the one that

i probably like the most

is this one

the event loop is what allows node.js

to perform non-blocking i o so input and

output operations despite the fact that

javascript is single threaded by

offloading operations to the system

kernel whenever possible

and as you can see i'm reading straight

from the node docs

now don't beat yourself up if this

sounds like a lot of gibberish there's a

reason why one can dedicate the entire

course just for event loop it is a

pretty complex topic but

one word i do want you to remember

is this offloading and you'll see why in

a second also don't worry i have

prepared more examples as well as some

slides to get my point across but just

in case you're not happy with my

examples

or you just want to explore the note

event loop in greater detail here are a

few external resources i find

particularly useful

when it comes to blog posts

just go to your favorite search engine

and type node.js

event loop

and the one that i find really useful is

this one

and the resource is nodejs and not.org

but it is dot dev

and then follow the link and here they

cover event loop

in great detail with a lot of cool

examples and pictures and slides and all

that good stuff and when it comes to

videos i would suggest going to youtube

and then just type event loop and the

first video that's going to pop up is

going to be the event loop bot in

browser javascript

and i'll talk about it in a second

and the nodejs specific event loop video

is this one i believe it's 15 minutes

long and you can see the name over here

so this is a very very useful video

where the speaker covers a lot of useful

details about node.js loop in great

detail and the reason why i'm suggesting

the first one as well

well

what is the language that we use

in node

that of course is javascript right and

even though there's some differences

between the event loop

the one that we use in the browser and

the one that is in the node.js

if you understand the concepts behind

the event loop that we use in a browser

trust me you're already halfway there to

understanding how the no js event loop

works since it's such an important topic

like promised i have prepared some of my

own resources as well we'll start with

the slides and move on to the closed

examples in next video

as a side note i made all the course

slides available on course api.com again

their website name is coors

api.com and once you click on the slides

link

you'll see all the slides

and i would want to start our discussion

by taking a look at what it means that

javascript is synchronous and single

threaded and effectively it's just a

fancy way of saying that just repeat

everything line by line

so for example if i have console log

with first task

then i have a for loop that takes some

time in this case two seconds but that

could be 10 seconds that could be 20 or

whatever and then i have another console

log of next task

javascript will just start reading

everything and it will read it line by

line and if this takes a long time it

will only run the next test once it's

done performing this time consuming one

so hopefully that is clear that

javascript just reads everything line by

line

and now let's take a look at our second

slide and in here we can see the

solution

if we would want to offload something to

the browser so when we're building

browser javascript apps we have this

option

of offloading to the browser now of

course it doesn't mean that we can

offload the for loop that's not going to

work this effectively is still going to

be the blocking code but browser nicely

provides the api

where we can offload those tasks to the

browser and only when the task is done

then we execute the callback and

probably the example we have done the

most is the fetch essentially when we

make the network request but we can also

do that for example with a set timeout

so i still have console.log with first

task but then even though my set timeout

function

has the second argument of zero so

essentially i have set timeout function

i provide the callback function that's

going to be executed in certain amount

of time

even if this is zero meaning you would

expect this one to run right away it

only runs after the next task so once

javascript is done executing the

immediate code

only then it executes the callback so in

this case we have the set timeout the

api that is provided from the browser

and we just said that we would want to

execute that e in zero seconds so

effectively there is no wait time

however javascript will first execute

this code and only then will execute the

callback so that way we can offload

those time consuming operations to the

browser again it doesn't mean that we

can offload for loops it means that

browser does provide some apis

where we don't have to write the

blocking code now let me be very clear

though when i say we cannot offload for

loops

what i mean is that we can still

write blocking code in javascript

but the browser does provide some nice

apis where we can offload those time

consuming tasks

and that brings us to our

main friend the nodejs event loop again

before i go over the example let me

stress something event loop is somewhat

complex and this is just to give you a

general understanding

so let's imagine this scenario i have an

app and just like any cool app

i have subscribers or users or however

you would want to call them and in this

case since my app is so so popular i

have eight of them

and what do the users do well they're

probably being annoying and they're

requesting something from the

application and as the requests are

coming in

the event loop is responsible for

avoiding this type of scenario

so let's imagine this i have all these

users the requests are coming in

but larry the little

decides that

in his request there's going to be

some kind of time consuming i don't know

database crawl or something like that so

effectively he's requesting something

and behind the scenes in my code that

means that i need to perform something

that takes a long time

so

in this case

the event loop just registers the

callback so it registers what needs to

be done when the task is complete

because if the event loop wouldn't do

that then we would have this scenario

where the requests are coming in

and because larry is requesting

something that takes a long time the

rest of the users would have to wait and

essentially it's not that the actual

operation takes a long time it's just

the fact that we're wasting our time

on waiting for that operation to be done

and only then we can serve the other

users but what the event loop does it

registers the callback and only when the

operation is complete it executes it now

keep in mind that again we're not

executing this right away

when we can effectively it's the same

scenario where we run our immediate code

first

and only then when we have the time we

execute the callback so for example in

this scenario if i would have hundred

console logs

after the next task

i would run them first and only then the

second task would appear here regardless

of what is the time set in here because

again we're running our immediate tasks

first and only then we run the callbacks

so the same thing happens here

where the requests are coming in let's

say that the operation is complete we

first registered the callback operation

is complete and instead of executing

that callback right away

it effectively gets put at the end of

the line and then when there is no

immediate code to run then we execute

the callback hopefully that is clear

event loop is our best friend because

with the help of event loop we can

offload some time consuming operations

and effectively just keep all our users

happy all right and once we have looked

at the event loop in theory

to hammer this home let's also take a

look at some code examples where we can

see event loop in action

as a side note all code examples are

located in the event loop example

directory so if you need to take a look

just grab the repo and you can find it

there and you should be familiar with

our first example

since it's a async version of read file

method

so we import read file from the

fs module and then we have console.log

started our task first

then we have

read file method where we pass the path

we pass the encoding and then of course

we have the callback

and then in the callback i cancel logged

first result and then of course i have

completed the first task

and then right after the read file

i have starting next task

and something really interesting in a

console i can see that

we first cancel logged started the first

task

then i right away have

starting the next task and then of

course once i'm done once i get back my

result then of course i have hello this

is first text file and of course

completed first task and again the

reason why is this happening because

read file

is a synchronous

and we already know that

event loop will offload this in this

case to a file system

so we start reading the file

notice like okay run this line of code

then offload this one and only when i

get back to the result

then

run the callback so

when the file system responds with error

or the data

then we invoke this one all right so we

offload this task and we just keep on

reading the code that's why we have

started the first task starting the next

one so right away go to the next test

and this one this asynchronous one well

we're just offloading

and then once the response comes back

whether it's an error whether it's a

success only then we invoke the callback

hopefully that is clear now as far as

this comment

i only added this one because we need to

keep in mind that of course i'm just

grabbing this code from the file

but the file is sitting in the folder

so if you were to run

nodemon and then directly the filename

which is of course going to be in the

event loop the path won't match so this

path only matches because of course i

have app.js but if you'll try to run

this code directly in this file that's

why it's not going to match and you need

to go one level up now my assumption is

that you're running it the same as me

and you're running that with npm start

that's why i kept the path

matching to the one in the app.js now

our next example so let me clear my

app.js i can close the read file as well

as package.json and then the next one is

set timeout so select here everything

and copy and paste in my fgs i'll

restart and then i have two console logs

and the third one is e in a set timeout

and this is pretty typical example for

javascript loop as well if you have

taken javascript courses which again i

assume you have since you're watching

the note one you probably remember this

example where i got you here is

following yeah i have the

console log

first and i have the second and third

and you think that since set timeout is

set to zero

so since we're saying yeah call this

callback function but actually wait only

zero seconds you'd think

that the order would be first second and

third right well wrong because we have

first third and second

why well because set timeout is

asynchronous correct and what happens

with asynchronous well they get

offloaded so in this case we run first

third

and then the second

because this one gets offloaded again

this one goes to the back of the line

and only when we're done

with our immediate code pretty much with

our synchronous code only then we invoke

that callback all right now i also added

these comments here where i have started

operating system process and then

completed and exited the operating

system process and the reason why i'm

showing you that because in next two

examples we'll do something a little bit

different so now i would want to go to

set interval

and by the way it's going to be a bit

clearer if we run here node and then

app.js so let me stop this and i'll go

with node and objects and you'll notice

that we started the operating system

process and then the moment we're done

with the code that's it we exit now if

we'll take a look at the set interval

you'll notice something really

interesting where if i go with node and

app.js notice something interesting and

by the way of course i didn't copy and

paste so go to the third example

and then just remove all this code and

copy and paste so that's my third

example and in here i have the set

interval now again yes we'll have to run

few times node app.js

and now check it out

so what i see here is

i will run first

so that's my console log

and then i have the set interval

and notice how we're not exiting the

process here

so we start the process similarly to the

second example

but if in the second example we actually

exited because we completed all our

tasks

in this case we're not doing that why

well because set interval is

asynchronous

now the difference between the set

timeout and set interval is the fact

that set interval

runs in those increments in this case of

course it is those two seconds so every

two seconds the

event loop

is just gonna invoke that callback now

that's why we're not exiting

that's why we're still in the process

and we can only exit the process if we

kill it so that would be control and c

or there's some unexpected error

otherwise it will always stay alive now

again keep in mind one thing where

notice i will run first

was first why well because again this is

asynchronous and i know i've said this

before 20 000 times but again this is

probably the core building block of no

the fact that

every time we have some asynchronous

action it's just going to be offloaded

and then when it's time we invoke the

callback and our last example is a

server and again i just wanted to

showcase how the process stays alive

so i'll take all the code

and copy and paste in app.js

now i'll stop this one so stop the

process and then we'll clear the console

and again

just to showcase how the process stays

live i'm going to go with node and

app.js and i'm doing that so you're not

confused with nodemon and then check it

out so we have server listening on port

5000

and then every time the request comes in

well we invoke this callback and in our

callback we're simply cancel logging

request event and then we send back the

hello world so now if i were to go to a

localhost 5000 there it is

i have the response of hello world and

in a console i'll see this request event

and check it out how again this process

stays alive

why well because listen is asynchronous

and the moment we set it up now event

loop

is just waiting for those requests to

come in

and then once they come in then of

course we run our callback now please

don't confuse this callback with what

we're responding

our request i went so this callback is

just when we're setting up the server

because in here we can have the success

over there so in our case as you can see

everything went great we have server

listening on port 5000 but of course

there also

might be an error and this one of course

just responds to that request event but

the whole point is with server.listen we

just say hey event loop just keep

listening

for those incoming requests and the

moments show up

then respond to them appropriately

hopefully it is clear and of course we

can move on to our next topic all right

and up next i want to talk about

asynchronous patterns in node.js

so if we remember

when we were setting up the file system

module

we covered how we have two flavors we

have the synchronous one and the

asynchronous one

and while asynchronous one is great

since we're not blocking the event loop

the problem is that if we're using this

callback approach

well it gets messy pretty quickly right

because we're nesting one callback

inside of the other one so now in the

following videos i would want to show

you the alternative that we'll use

throughout the course

and why in my opinion it is much cleaner

syntax and that's why of course we'll

use it and first what i would want is

just to kill everything here and i'll

start with the nodemon

since

i'm done showing you the event loop and

we're just going to go with npm start

right that was the proper one and now

i'll delete everything that i currently

have not here sorry so i'll leave this

one the async one i would want to remove

everything in the app.js

and now i just want to quickly show you

the code that would block that event

loop again this is going to be the video

where

if you don't want to

code along you don't have to you can

just sit back and relax

and effectively you'll be in good shape

and again we'll set up the server like i

mentioned before already 20 000 times

don't worry about specific commands

we have rest of the course where we'll

be building servers so trust me you'll

get sick of it so go with http

and require

and of course we're looking for http

module

and then remember the methods create

server and listen

so we go with const and we create the

server

that is http

and create server we pass in callback a

callback takes two objects request

object and response object so again

essentially request object is what is

coming in and response object just

represents what we're sending out what

essentially we are responding and then i

would want to listen on a port again so

i run server.listen and then i'll pass

in the port of 5000 and then of course

we have that callback once the server is

ready and in here we can just go with

console.log

and we'll simply say

server is listening on port

5000 server is

is listening or just listening

listening

on port and then of course in my case

port is 5000

let's set that up so we should have this

listening on port 5000 and then of

course in my callback function i would

want to check 40 urls because i want to

show you how even if we try to get a

different resource we're still blocked

by other user

if he or she is requesting some kind of

resource where we have the blocking code

and don't worry if this sounds like

gibberish you'll see what i mean in a

second so remember on the request object

we could check for the url

so effectively you could check what is

the resource that the user is requesting

so for example home page would be

forward slash and then the about page

would be forward slash and about and

that is sitting in the property by the

name of request and url so request is

the object and then url is the property

so again we'll do a quick and dirty way

we'll just say request url is equal to a

forward slash that means it's a homepage

and then we just need to go with a

res.end

and then we'll say home page again later

we'll have way more sophisticated

approach but for now this will do

and then we're checking for the about

page

okay

awesome so this is going to be an about

page and then

if there's a page that doesn't match

any of the resources

then of course i'll just send back

i don't know error page i'm not going to

set up the whole link nothing like that

all right we save it and then this

should send back about page awesome and

then of course in home page i can just

respond with the homepage so life is

beautiful users can come here and as a

side note multiple users i'm

representing with these tabs so imagine

these are my users and life is beautiful

we are requesting resources and we're

just going on about our day now the

problem is going to be if i go to about

and if i set up some kind of blocking

code now what would be a blocking code

well that could be

a nested for loop

so i'm just going to go with blocking

code and then i'll add some exclamation

points and let's simply set up a for

loop let's say i

is equal

to zero

and then let's say i is less than

thousand

and yep i plus plus so

every iteration will increase by one

however

i'll set it up as a nested portal so

copy and paste and i'll just change

these values

to j

so j here and j here

and then let's just cancel log

and we'll say j and i again doesn't

really matter what we type there just

say i

and j

now known dialogue question what do you

think is gonna happen

so if the user navigates to about i mean

we can kind of see that this will take

some time

right

now you would expect though that

only the user who navigates here

gets blocked

and

you'd be wrong because we'll also block

the other suckers who are just trying to

get to the homepage so let me navigate

here

and check this out so i run this one and

notice how we're loading now the same

thing happens here now and here

okay and only when we're done here

then these two can get the resource

again

now of course if i go

to

my project i can see that in the console

i have all these values right because i

have this blocking code i have the

synchronous code that just takes a long

time and this is just a representation

of why

we prefer this asynchronous

now yes at the moment this is messy and

don't worry in the next videos we'll fix

it but this hopefully gives you an idea

why you should always strive setting up

your code asynchronously

because what we've learned in the

previous videos

if we do that

then those tasks

are offloaded and then only when the

data is back only when it's ready

then we invoke it and that way we're not

blocking the other users hopefully it is

clear and now of course let's take a

look at some other patterns we can use

so we still get the benefits so we're

not blocking that event loop

but

we also have a cleaner code

where we don't have this nested callback

mess all right and once we have covered

why it's so important to use the

asynchronous approach

now of course let's clean up our f a a

sync

so instead of using these nested

callbacks let's see a nicer pattern and

as i say note if you want to see the

code

that we wrote in a previous video and

the one we are about to write then the

files are located in two async patterns

folder so i'll close everything for now

and then back in app.js

i can remove it like i said if you want

to access that code it is sitting in the

two async patterns folder and we'll

simply start by recreating the

read file setup where i'm gonna go with

const and i'm right away accessing that

from the file system module and i'll set

it equal to require of course and then

file system all right that's awesome we

know that it is asynchronous so we need

to set it up with three parameters we go

with read

file and then we would want to pass in

path first so again since i'm in app.js

i'm going to be looking for the content

and then forward slash and then first

txt the file we already created before

then we have encoding so comma and then

again we're going to go with utf-8 and

then last one is going to be that

callback where the first value is the

error and then the second one is the

data that we're getting back okay

awesome so once the file system responds

then of course we invoke this callback

and inside of that callback we have our

logic so if there's going to be an error

for time being

i will just return like so

and then if i have the data i'll set it

up as else so say here console log

and data of course

and we shouldn't be surprised

if we've seen a console hello this is a

first text file because we already

covered the setup right so we're passing

the path we pass in the encoding and

then we set up the callback now the

problem starts if we would want to

perform

multiple actions if i want to read two

files and then for example write one

correct so what would be a better

solution well a better solution

would be turning this into a promise and

then eventually we'll set up async await

now please keep in mind that the only

reason why i will type out the promise

stuff is because i would want you to

understand what is happening behind the

scenes but don't worry throughout the

course we'll just stick with a sync and

a weight syntax and essentially you

won't have to worry about what is

happening behind the scenes but the

first example yes i want you to

understand everything in detail so what

we could do is create a new function

and we can just say const and then

i'll call this get text now this get

text will take a path

since i want to read two files and then

eventually write one as well just like

we did here and of course the goal here

is to showcase how we can make the code

in the file fs async at least that's how

i called my file much cleaner and more

readable so again we pass in the path

and then what i would want to return

from this function is a promise so we go

with return

new promise and then in the promise

object we need to pass in is another

callback function so we pass in the

callback function and in here we pass in

two more functions one for resolve and

then one for reject and then once i have

set up both of these parameters now of

course what i would want is to move the

read file

and place it inside of the promised one

okay so once we place it here first of

all notice here how i'm passing in the

path so of course i can change this one

around so i can say path and then the

encoding stays the same

as well as the callback however inside

of the callback once i have access to

resolve and reject what i could simply

say that if there is an error

i will spit back the error so say reject

an error and if everything goes great

now of course let's go with resolve and

then we'll pass in the data and once we

have this setup what's really cool that

now i can invoke get text and this is

going to return a promise and then of

course we can chain that then and catch

so below the get text i can go with get

text and of course we're looking for the

path so we still would need to use dot

and then forward slash and then content

of course and first txt so that's the

path and then like i said

we are returning a promise so we can

chain that then

and of course here i can have the result

and i'll just cancel log it for now

or result and then i can also chain that

catch and here i'm passing in the error

so again we can't log it

and we simply would want to see the

error i save it and beautiful

again in a console i have hello this is

first text file so i know that it worked

and also if i change the path

so if i make my path incorrect we should

see in the console the error

where of course node cannot find file so

if that works now of course we can take

a look at how we can make it even

cleaner by setting up async 08 and once

we have our initial setup once we have

turned this into a promise

technically we're not out of the woods

because if i would want to perform again

two file reads and then eventually write

the file as well and if i would want to

do all of that asynchronously it's still

going to be paying just by using the

promises so what would be a solution

well since we're returning a promise if

i use async await

i can wait till promise is settled

and then decide what i would want to do

and the way we set that one up is by

creating a new function now please keep

one thing in mind where

eventually throughout the course

those functions that i'm about to set up

are going to be provided to us

so we'll just attach that async to the

callback functions that already provided

us by the libraries okay but in this

example i'll have to create one from the

scratch and again the whole point here

is because i would want to create a

function a start function that i'm going

to set up as a synchronous function and

i would want to attach a weight

so i would only respond once the promise

is settled so in here i go const start

and that's my function but i need to set

it up right away as async because i

would want to use my await keyword

correct and then we simply go with const

and i know that of course i'm looking

for the first file

and i'll just say first and that one is

equal to

get text and basically i want to pass in

the same thing here now i do need to

place this one in quotation marks so my

bad i messed it up a little bit okay i

passed it in and that should do it

now of course what i'm missing here is a

weight so i had this await and now only

once the promise is resolved

then i'll get my response so what i

could do here

is just comment these two or you know

what this one i cannot comment out yet

don't worry we will eventually

this one i can comment out and then

maybe

move this below

okay so you don't think that i'm running

this code and since i have my function

now of course i would need to invoke it

so invoke start

and check it out now of course i don't

have the error which is a good sign i

guess

and then we'll simply go with log and

none first

and notice the difference

where previously when we were setting up

the callbacks we had to nest everything

now i'm waiting for this promise to be

resolved and only once it's resolved

then of course i can do something with

the value now every time we have this

async await approach what we would want

is to wrap this e in the try catch block

so if something goes wrong then we have

at least a little bit of control over it

so i'll set up try catch block and then

i'll set up my first await and

eventually we'll add here more

and then in the error i'll simply go

with console.log and we'll console log

the error and let's just save that one

so now we have nice try and catch block

and by the way sorry i deleted it we'll

still take a look at the first one and

then if we change the path

then of course we'll get an error okay

so that's good now i have my start

function it is the synchronous i'm

waiting for the promises to resolve

they're all wrapped in try catch block

so what's next well if you remember in

here

what were the actions that we were doing

well we read two files correct and then

we wrote one okay so let's try that one

with this new approach where essentially

i have first so just copy and paste and

then i'll look for the second file

remember

we should have that in the content so

this is going to be the second one

second over here and then i would want

to write the file now of course

you could say well the problem here is

going to be that i'll have to

write a new wrapping function to set it

up as a promise because

yes we can of course read the file but

functionality for the write file again

we would need to wrap it

don't worry there's a way how we can get

this actually out of the node

first i just want to showcase how much

cleaner this already is

where i can just wait for first

second like so and now notice in the

console hello this is the first text and

hello this is the second file again i

fully understand that you're looking at

this wrapper function and you're like

well this definitely doesn't look that

much cleaner than this one don't worry

there's a way for us to get those

functions

in a way that they're already returning

a promise what i would want you to focus

on

is this code what i would want you to

understand that this definitely

is much cleaner than what we have here

we read the file and then we set up

another nested callback

and another nested callback and

hopefully you get the gist

waiting for these promises to resolve is

definitely a cleaner and more readable

approach all right so this works we have

our start function it is asynchronous

we're waiting for prompts to resolve and

we can see that it is already much

cleaner

how we can set up this code

without the wrapping function

well what's really cool that in node

there is a module by the name of util

and we just go here const and we'll

assign it to a variable and we'll just

be looking for require of course

since we would want to import the module

and again the name is util

and then instead of this module we have

a method by the name of promisify

and with the use of this function we can

take our read file which of course was

looking for the callback and turn it

into the function that returns a promise

and again this is over simplified

version what is happening there but

hopefully you understand that as a

result we'll get again this promise back

now the way we'll set that up of course

we have read file here already so i

cannot use the same name that's why i'll

go with read

file and we'll call this promise and

that one is equal to util that is of

course my module dot and then notice the

function promisify and then we pass in

that read file function so now i have my

promise one so now what i could do

is first of all comment this out and

move it down

again so it stays for your reference

but

it doesn't compromise my view

and of course now i have the error

because

well get text is not defined that's fine

don't worry and i'll copy and paste and

since i also want to write a new file

i will get from the file system one

the right file function and then i'll do

the same thing

where in this case it's going to be

called

write file promise

and then we pass in write file

and of course now instead of calling

get text what i'm gonna do is go with

right file or i'm sorry in this case

we're going for read file promise and

then keep in mind one thing where this

is not a get text one so we're still

looking for the path

as well as the encoding that's well copy

and paste and then second argument we

pass in is the encoding and again our

functionality shouldn't change where i

should see in console the results from

the first txt now of course i want to do

the same thing with the second one so

have read file promise second txt

again we have to pass in the encoding

otherwise we'll get the buffer back

so copy this and paste and again if we

cancel log it there it is we have hello

this is first text file and this is the

second one and since in the line 4 we

passed in

write file into promisify of course what

we could also do is right away write the

file so i can go with await and i'm

simply not assigning this to a variable

because well i'm getting back on the

finder as far as data and i'm just going

to go with await

write file promise and the same spiel we

pass in first the path and in this case

of course if the file is not there

node will create one

and the name will be result and i'll

just call this mine

grenade and then txt and then the second

one is data so for that one i'll set up

my template string and i'll just say

this is

awesome

awesome

and then let's set up the colon and then

we'll access both

first

as well as the second one so we'll

interpolate both of them

second

and then once we save

if we take a look at the content there

it is now we have the mind grenade one

correct now there's probably one where i

was testing yep there's one where i was

testing so i'll remove this one but if i

take a look at dtxd1 then of course i'll

have this is awesome hello this is first

text file and then i have the second one

now what's even more cool

that technically we can even skip this

part as well again

i'll leave this one for your reference

but

if you go to require

and then you require of course file

system module but if you add dot

promises

what do you think is going to return

well effectively the same thing so now

of course i just need to change the name

from read file promise and write file

promise back to read file and write file

since those are the two functions that

i'm importing and that will right away

return promises and again we save and

remember that by default we're just

overwriting stuff

so if i were to go

and add a third argument my options one

and if i'm just going to say

flag and i'll set it equal to upend once

we save well now we have this is awesome

repeat it one more time again just to

showcase that our functionality still

works

i fully understand that there was a

little detour

where we created our own wrapper

function

and then we covered how we would consume

promises but hopefully this helps you

understand that this approach is

definitely way better

so it is more readable it is more

easier to wrap your head around and

that's why for the remainder of the

course we'll stick with this one

again

some things will be provided

to us by default so libraries will

provide the functions that return

promises will right away have the

callback functions that we'll just set

up as async and hopefully you get the

gist so a lot of things will be given to

us but the core functionality won't

change where instead of using callbacks

and nesting them inside of the other

callbacks and nesting more and more and

more

we'll set up everything with async await

because the syntax is cleaner and way

easier to read

excellent once we have covered async

patterns we're going to use throughout

the course now let's talk about events

in node.js

when working on browser javascript apps

a big part of our work

is to handle events for example

user clicks a button

and of course in our program we handle

that user hovers over the link

and again same deal in our program we

are handling that and hopefully you get

the gist essentially as our program

executes at least in part it is

controlled by events

of course depending on a program but

it's safe to say that in browser app

those events are mostly external

now that style of programming is

actually called event driven programming

and effectively it's just that a style

in which the flow of the program

is at least in part determined by the

events that occur

as the program executes

now it's easier to imagine that of

course

when you have a gui right the graphical

interface

just like the button and links example i

just mentioned

but what about server side

is it also possible and of course the

answer is yes in fact event driven

programming is used heavily in node.js

and in the following videos we'll see

some of the examples of it

and basically the idea is following we

listen for specific events

and register functions that will execute

in response to those events

so once our event takes place callback

function fires just like in our

imaginary button example

now before we continue let me stress

something our first examples are going

to be basic and

even somewhat silly

but don't let that fool you

many built-in modules in node.js do use

events under the hood and therefore

making events and event driven

programming a big part of nodejs all

right and once we have covered general

concepts behind events as well as

event-driven programming now let's set

up our own events in node and the way we

do that we come up with a variable and

typically this name is event

emitter because what we're getting back

is the class

and we require the events module so

require events module and we assign it

to a variable which essentially is a

class

and again a common practice is calling

this event emitter and at this point you

have two options if you want to create

something custom

you'll need to

extend the class

or if you simply want to

emit an event

as well as listen for it then you can

just create the instance so go with the

second route we'll go with const and

then whatever name you would want in my

case i'm just going to call this custom

emitter like so and i'll assign it to

new

emitter so event emitter or however you

call this variable and we just need to

invoke it so now we have the instance of

our class so essentially we have the

object now there are many methods in

this object however two that we're

interested the most are on

and emit

so on we'll listen for specific amend

and then emit of course will emit that

event

and the way we set it up we go with

custom mirror or whatever name you used

and then we go with on

and at the very basic setup in the on

method we just pass in the string

where we say the name of the event now

in my case i'll name my one response and

then of course once i have subscribed to

it i also would want to pass in the

callback function so essentially when

this event takes place

well then i would want to do something

and in my case i'll just go with

console.log and we'll simply say data

received or i'll place this one in the

template strings and you'll see in a

second why so we'll go with data

received

and then eventually there's going to be

some more data and of course once we

have subscribed to this specific event

now i would want to admit it and the way

we do that we just go with custom

emitter and of course the method is

surprise surprise emit and of course at

this point

these strings need to match so if i'm

emitting

the response event

and just say here response and what

you'll see in the console is wherever

you have in callback so of course in my

case i have console log data received

and then once i run it i have data

received in console so that's the most

basic setup when it comes to events

again we create an instance from the

class that we get back from the events

module and then we have two methods we

have on method as well as the emit

method and then in the on method we pass

in the string so that's going to be the

name of the event as well as the

callback function

so once this event takes place

then of course we would want to do

something and in our case we'll just

console.log data received and then once

we have subscribed to this event then of

course we need to emit it and the way we

do that we just go with

whatever the name is in my case custom

emitter then emit method and then we

pass in the same string that we're

listening for

in our case of course response and then

the moment we do that

we of course have whatever is in the

callback function which in of course of

course is just a simple log data

received

all right and once we have covered the

basic setup now let me show you some

things that

i would want you to be aware of

first

we can have as many methods we would

want so for example we have the same

event we have here response correct and

we are omitting it so nothing stops me

here just copy and paste

and listen for the same event

which of course in our case is this

response and then do some other logic in

my callback again in my case it's just

going to be simple

different kinds of log so i'm going to

say some

other

logic here and i'm not going to copy and

paste

the same function 20 000 times just to

prove my point but hopefully understand

that yes we can emit our event and then

yes also we can have as many functions

we would want here that our listening

for that event and do some other logic

so that's point number one point number

two that i would like to make is the

fact that

this order matters

so we first listen for event and then we

emit it so for example if i will place

my emit above the second function or

above both of the functions which you'll

notice

that i have nothing in a console

why well because i first emit the event

and only then i listen for it

as you can see that doesn't make sense

so first we would want to listen for the

event

and only then we would admit it so in

this case notice i don't have this some

other logic goes in here because i

listen for response and then i right

away admit the response and then again i

listen for the response but i already

admitted the event correct so it doesn't

make sense to listen for the event once

it has been already emitted so that's

the point number two

and then thirdly our also on a showcase

that we can pass the arguments when

we're omitting the event so for example

i go here with my emit i pass in the

name which is of course response and

then i can pass in more arguments for

example here i'll go john and then the

id number 34. so string and a number and

then in my callback function

i can access those arguments as

parameters just like normal functions so

in this case i'll call them name and id

and simply in my console.log i'll say

name

and the second one will be with id

and then whatever is that id

now i'll add here data received

user and then save it and it's no

surprise that in the console i see data

received user john with id34 now in the

second function as you can see

i wasn't looking for those arguments i

just don't have access to the arguments

because i don't have the parameters but

it's not like everything broke just

because in the event i passed in the

arguments and lastly i would just want

to reiterate the point that even though

you might not write

your own events events are a core

building block of node and effectively

as you're building and writing out the

code for your node application you are

using those events at the end of the day

anyway because a lot of built-in modules

rely on them and as a quick side note if

you'd like to see the code that we wrote

in previous two lectures you can just

navigate to 13 event emitter and in

order to show that i'll quickly set up a

server

and again the code for this one you can

find at 14 and then request event so

copy all the contents from the file

and then just copy and paste

and notice something interesting where

again yes we're getting the http module

and remember the setup that we have used

so far where we go with http create

server and then we pass in this callback

function

and then of course this callback

function will be invoked every time

someone visits our server so every time

the request

comes in now there's another way how we

can set it up by using event emitter api

so we still create a server we go with

http and then create server function but

instead of passing in the callback

function like we did previously

server has the method

on

does that ring a bell remember our

previous example

we had our own instance and

it had the method of on correct so the

same goes for server so server has the

method on

and we listen for

request event and when that request

comes in

then of course again we have this

callback function that handles it so

behind the scenes

server emits the request event and then

of course we can listen for it we can

subscribe to it listen for it or respond

to it however you'd want to call it and

the way we do that we go with server on

and then this is a specific name

because of course it emits that specific

name behind the scene so make sure that

it is a request and then the same spiel

now how do i know that well if we go to

node documentation and if we look for

http we keep on scrolling keep on

scrolling eventually we'll hit the

server

and

over here i can see that it has a clash

okay that's a good start and that what

do you see here

well i see the event right and what is

the event well the name is request so

that's how i know

that my server the instance that i

create has the ability to listen for

request events and if you want to dig

deeper you can just click on a server

you notice that it extends the net

server and if we keep on digging check

it out so this one extends what it

extends the event emitter so hopefully

that makes it clear that even though you

might not be setting up events on your

own a bunch of built-in modules rely

heavily

on this concept of events all right and

up next we have streams in node.js

and at its simplest streams are used to

read or write sequentially basically

when we have to handle and manipulate

streaming data for example continuous

source or a big file streams come in

real handy

and now there are four different types

of streams we have writable used to

write data sequentially then we have

readable used to read data sequentially

duplex

used to both read and write data

sequentially and also transform where

data can be modified when writing or

reading just like with events many

built-in modules in node implement

streaming interface

and what's also interesting streams

extend event emitters class which simply

means that we can use events like data

and and on streams

since streams are somewhat off an

advanced topic in node i'll try to keep

it short and sweet mostly by showing you

examples of streams and hopefully that

way you get the main idea without being

overwhelmed

all right and once we know the theory

behind the streams now let's take a look

at the practical example

and a very good use case is using

streams when we are reading files

because we need to understand one thing

where when we use the sync or

asynchronous approach what happens we're

reading the whole file and of course in

our example we were setting this equal

to a variable correct but if we have a

big file

well first of all you're just using all

that memory and second

as the file size gets bigger and bigger

bigger eventually the variable is not

going to be good enough you will get an

error that

i mean the size is too big and you

cannot place everything in the string so

what would be a solution one solution

would be read stream option

and the way we'll set this up

i'm going to start app.js from scratch

but if you take a look at the repo

you'll notice this 15 create big file so

previously when we were working with

files i just had some small files right

so i had the first txt blah blah blah

result and whatever now before we set up

the read stream i would want to create a

big file again this is optional you

don't have to do that but in my case in

order to show you how the streams work

yes i'll have to set up a big file and

first i'll remove it because of course

i already have it since i was testing it

and now i'll stop my server and of

course in my case i'll run 15 the create

big file js

if you want to set it on your own and if

you don't want to use the repo you can

just

get the right file sync from the fs

module and then notice i have the loop

where i believe i have here 10 000

and then every iteration i just write a

big txt i of course i have the flag

upend and then i'm just adding hello

world and starting a new line so if i'll

run node

and then of course i'm going to go with

my file name which is 15

then hyphen

create

big

file and js like so

then in the content i should have this

big file

and once i have my big file i'll go back

to app.js and i'll use my npm start

since of course i have known mine in

place and then let's go with cons now

i'm not going to show you how the setup

would look like with file sync or the

asynchronous one again hopefully you

understand that the setup would be

exactly the same like we have in 10 and

11 where we had the fa sync and fa async

and now of course let's just go with the

stream option so the method name is

create

read

stream and we require that from the fs

module like so

and then

we create a new variable and in my case

i'll call this stream and we invoke the

create read stream and the only thing by

default we need to pass in is the path

so of course in my case i'm going to go

with content and then forward slash and

since i just created that text file the

big one of course i'm going to go with

big txt and now remember the good old

friends events well

once we create this instance we actually

have access to them and the ones that

we're going to use is going to be data

and error so we can go with stream

and then on and remember the event

syntax and then the event that you would

want to listen for is a data and then we

have our callback function and again it

is a parameter so we can call whatever

we would want but in my case i'm going

to go result and let's just console.log

the result like so

and what you'll notice

is that we have

64 kilobytes here that's our first

console log then we have another one 464

kilobytes and the reason why i know that

is because by default that's the size

we're getting and then we're getting the

reminder now just to prove my point i'm

going to go to my folder

and i'm going to look for my content

and then in there if you take a look the

big text file we created is

169 kilobytes so as you can see now

we're reading data in chunks

and by default that chunk is 64

kilobytes

and every time we cancel log

we see that we have 64 64 and eventually

we have the remainder so instead of

reading everything and placing that in

the variable we're doing that in chunks

and as you can see we're using the event

and the event is data and in order to

hammer this home why don't we take a

look at the docs

so first i'm going to look for my file

system

and then let's look for

our create read stream so we go here as

we can see we have this class read

stream and then on this class we have

these three ones we have close open

and ready and as a side note we'll use

this one a little bit later as well the

open one so keep an eye on this one and

then as far as the read stream well as

you can see it is created when we go

with create read stream and invoke it

right so i got the create read stream

that's my function i just passed in the

past and i invoked it and in turn

that returns

the read stream

right then

actual read stream extends from

stream.readable so right away i have

these events i have close open and ready

and like i said we use this open a

little bit later now since it is

extending from the stream check it out

now of course i have the data one all

right so this is a chunk of data

and as you can see every time we are

getting that data

we can do something with it now at the

moment we're just going to logging it's

very simple but eventually as you can

already imagine we can do way more

useful things than that beautiful once

we understand the basics now let's take

a look at some additional info like i

said by default the size of the buffer

is going to be 64 kilobytes however we

can also control it and the way we do

that is by passing in the object when

we're setting up create read stream so

first argument is going to be the path

which again in my case is going to be

that big text file that i created using

my file using my for loop and then i can

pass in the options object and in there

the property that you're looking for the

property that controls the size of the

buffer

has the name of high water mark so for

example if i go with 90 000 here then of

course you'll see that i'll have two

console logs

one for

90 kilobytes and the second one will be

remainder again keep in mind that

our file size is

169 kilobytes that's number one number

two

we can right away set up the encoding as

well so i go with comma and then the

property name is encoding and again

we'll set it up equal to utf-8 like so

and then you'll see in a console of

course the hello world why well because

that is the content coming from the file

and lastly i also would want to mention

that we have the error event as well so

if i go with stream and then on and

we're checking for the error and as

always we can do something once that

error happens so that's our callback

function and in this case i'll just

access the error property and i'll

console.log the error so i'll say here

error and the way we check that one out

is by providing wrong path so in my case

i'm just going to add two dots and then

once i save check it out in a console

i'll have the error where it tells me

that no such file or directory

all right and now let's take a look at

the practical example when streams come

in handy now again this is going to be

one of those videos where you don't have

to code along you can just sit back and

relax and see how i struggle and first

what i want is to make it even a bigger

file so remember d15 create big file

i believe i had 10 iterations right so

i'm gonna add one more

meaning i'll add one more zero i'll stop

my server right now again this is

optional you don't have to do that and

i'll remove the big file

like so

and then i'll run one more time

the file with node

and then of course this file is going to

be way bigger

so let me navigate to my folder just to

showcase that

and i'm looking for content and now the

big file is 1.8 megs

now once i have the big file

i'll go with npm

start at the moment i just have the

stream example but if you want to see

the whole code just take a look at the

file number 17 and notice again we're

creating a http server and i'm just

using the read file stick method i'm

looking for big txt the encoding is

utf-8 and then i just place my variable

my text one into

res dot and method and effectively i'm

just sending my big text file

and let me restart the server

here so let me go with npm start right

now so let me select everything from

this file

and copy and paste

and now if we navigate to localhost

5000

we should see a bunch of hello world

now the problem with the setup is

following where if i go to developer

tools and if i take a look at the

network and if i refresh

yep

this request was successful

take a look at the size

do you think

it is the smartest thing to send these

type of files over the wire and of

course this is just going to make it

very difficult to all your users because

you're just sending large chunks of data

effectively i'm sending the whole file

and more specifically if i click check

it out so i have the request url okay

that is good the method is get

now as you can see the content length

is my 1.8 megs right

and you'll see in a second that once we

refactor this to read stream method

that we're sending data in the chunks

and again the best way to see that is by

looking at the headers where at the

moment i can see the content length and

that one is at 1.8 megs but once we

refactor that the setup is going to be

different so at the moment i have this

text i'm accessing that by read file

sync so comment this out and let's set

it up with our create read stream so

i'll go with const and i'll call this

file

stream and this is going to be equal to

fs and then create read stream now use

the same address

so use the same path

and then i'll use the same encoding as

well

so let's go with utf-8 okay

awesome and once we set up the stream

remember we have access to

to events

file stream on

and of course i'm going to be looking

for the open

and i'll have my callback function and

we'll set that functionality up in a

second and the second one of course is

the error so go with file stream and

then on and again we're looking for the

event by the name of error and then in

our callback function we can access the

error and i'll simply pass it in in my

response so if there is an error i'll

just grab the error from my parameter

and pass it in now as far as the open

here instead of setting it equal to

instead of going res dot end and then

text file stream also have the pipe

method so we can go to file stream and

then pipe and what the pipe is doing it

is pushing from the read stream into

right stream so you can imagine that if

we can read data in chunks we can also

write data in chunks and what happens

under the herd response object can be

set up as a writable stream so we have

our file stream so that's our read

stream we have method of pipe so we're

piping this into a writable stream and

now of course i'll pass in my response

object and if we go back to the browser

and if we'll refresh

now notice something interesting yeah

still same request right to localhost

5000 still same size but

if i take a look at the headers now i

can see that my response headers are

chunked so instead of sending our file

back in one large instance we're sending

it back in chunks awesome congrats on

completing section number three

node fundamentals and hopefully after

watching the section you have a good

general understanding of how node works

and now that we're big shots let's apply

that knowledge and build some servers

shall we and we're going to start

section 4 with the general info of how

the web works more specifically how we

exchange data on the web

and we're going to do that with the help

of few slides

now if you're one of the people who's

already reached a daily slide limit i

hear you

once we're done with these suckers i

promise we'll mostly actually write code

for the remainder of the course

i do believe though that before we build

an actual web server it's crucial for us

to understand how it works under the

hood and that way we'll have clear

understanding of what tasks need to be

done if something is iffy you can always

go back to the slides you already know

where they're located and also as we're

going to be progressing with the course

from time to time i will swing back to

them when i'll need to emphasize a

specific point

with that said let's talk about how we

exchange data

on the web

um it's safe to say that if you're

watching this video

you know how to use a web browser

but under the hood the way it works

every time we open up a browser

and we type the url so the web address

we're actually performing a request

and we are performing a request to the

server

that is responsible

serving those resources so for example

when you look for cnn.com

you're looking for a server that has

those resources and then that server

sends you back the response and the same

works with youtube the same works with

johnsmeld.com

or whatever so you just pick a resource

you say hey

can i get this data and then server who

is responsible for those resources just

sends you back the response now that is

done using http protocol and that's why

these ones are called http messages

so the user sends the http

request message and then the server

sends the http response message

and that's how we exchange data on web

and for the remainder of the course

we'll be responsible for building

such web server using node and more

specifically express now i'll talk about

it while we use express as well show you

a few examples

later on in a course but for now just

remember that yes we'll use node but in

order to make our lives easier we'll use

the framework by the name of express js

and lastly i would just want to mention

that even though name server definitely

sounds way cooler than the computer

at the end of the day they're just

computers whose job

is to always make that resource

available

so yes those are computers and yes there

are some differences for example

they most likely don't have the

graphical interface or the gui

and also they're probably much bigger

than your laptop but at the end of the

day they are computers

whose job

is to always make sure that that

resource is available because imagine if

you would have a server that only works

from eight to five so if you go to your

website at i don't know six o'clock at

night you cannot access the resource

probably that's not the service that you

would pick so next time when someone

asks you if it rains does the cloud

still work you know what to answer

because at the end of the day when we

talk about cloud cloud is just a bunch

of these servers bunch of these

computers connected together beautiful

and once we have a general understanding

how data is exchanged on a web

let's also cover how http messages are

structured please keep in mind that

since it's going to be a big part of our

job

we'll come back to this particular slide

more than once so if you're if you're

about something just please be patient

and i'll answer all of your questions as

we move along with the course with that

said the general structure

for both messages is similar they both

have a start line

they both have optional headers a blank

line that indicates that all the meta

info has been sent and effectively

headers are that meta info as well as

optional body and before we continue

again let me stress something so request

messages

are what the user is sending so for

example if you open up the browser to

search the web or that could be your web

application because remember with web

applications we also can make http

requests correct and then response

is going to be our responsibility so

we'll have to set up a proper server

that sends a correct response

and in general when we talk about the

request

message

in start line there's going to be a

method

then the url as well as the http version

now

we are mostly going to be interested in

these two things in the method as well

as the url now there's going to be a

separate slide about the methods as well

and don't worry we'll cover that in a

greater detail once we cover them with

actual code examples so i'll come back

to that slide just understand the

general idea that when we talk about

methods effectively we're communicating

what we would want to do so for example

if i want to get the resource i'm going

to set it up as a get request now if i

want to add the resource then of course

this is going to be a post request and

then of course you can read the rest now

why i'm displaying here this get because

that is the default request

that the browser performs

since when we open up the browser we

want to get some kind of resource

correct that's why we're performing a

get request and the url is just the

address and that could be for example

johnsmilk.com or that could be i don't

know espn forward slash basketball both

of them are just a web addresses now

headers

is essentially optional

where this is a meta information about

our request and just to give you a

general idea how the headers would look

like they would look something like this

so it is a key value pairs now don't

freak out

as you know when you search the web you

don't need to add them manually and the

same is going to be with our server a

lot of it is going to be taken care of

but yes some things we'll have to add

on our own basically this is going to be

information about our message

and then we also have optional body

so when the user is requesting something

if you just want the resource there is

nobody there's nothing basically what to

send however if we would want to add a

resource onto the server yes

then you are expected to provide that

data and it's also called payload so

again i might use them interchangeably

so that's the general structure of the

request message

we have the start line we have the

headers that is the information about

our message as well as the black line

which just indicates that we're done

with the meta information and optional

body which we'll use from time to time

and now of course we need to talk about

the response message so response message

is what we're going to be creating again

most of it will be done for us but some

parts yes we'll have to do it manually

and it's going to be our responsibility

so the start line

has the http version which most likely

is going to be 1.1

then we have a status code and status

text now when it comes to status code

it just signals

what is the result of the request so for

example notice here this 200

that means that request was successful

so that's what we're sending back and

yes there's quite a few of those codes

and as we move along with the course of

course we will cover them but please

please please don't rush over to the

search engine and start memorizing the

status codes pretty much as we're going

to be building the application i'll tell

you which code means what and for

example 400 means that there was some

kind of request error

so the user was trying to request some

kind of research and with 400 there was

a request error now for example the code

404 means that the resource is not found

so when i'm sending back the message i'm

like hey listen here's the status code

for the message if you are successful

here's 200 if there was an error for

example you get a 400 if the

request is unauthorized then you can get

401 and hopefully you get the gist and

yes of course as we're progressing we

will cover more status code then again

we have the headers

where basically we provide info

about our message our response message

and again like i said you won't have to

type everything line by line but

effectively it is a

setup of key value pairs and the ones

that i would like to mention are these

ones notice this content type we have

text html that is when we're sending

back the html but also our second option

is going to be sending back the data

so hopefully you are aware that when

you're building a web application when

we communicate with api most of the time

we're getting back the json data because

over the web effectively we just send

over the string so if for example i have

some kind of array we transfer this into

application json and i clearly indicate

that in my headers where i say that no

i'm not sending text and html i'm

actually sending a application json and

then that application who is requesting

the web application knows that hey from

the server i'm getting a content type

which is application json so for example

in that case i could send back here this

array with bunch of these objects and

just to give you a real-world taste why

don't we do this

open up a new browser tab and i'm simply

going to course api because i think

there's going to be less data so there's

going to be less clutter so go to course

api here and then you can either pick

the slides or you can just look at the

home page and if you inspect

and if you look in the browser tab

you'll find a network

and very useful one is this one where we

can just look for all the requests we

refresh and then check it out so these

are the requests

that browser performed and i'll talk

about it a bit later why there's also

this style css in fact that's going to

be one of our first examples but take a

look at this one so i have this course

api and then forward slash and if you

remember when we were building our

original server what i said that if we

have this forward slash that just means

home page so if we're just navigating to

courseapi.com

and

that is our homepage we simply add this

forward slash now of course in the

browser that's automatically added but

that's why when we're setting up the

server one of the cases is going to be

if the user navigates to the homepage

then we simply look for forward slash so

if for example you go to the slides

you'll notice that uh in this case i

would have to refresh notice here i have

the course api

forward slash slides so that is already

a page in my website correct so i have

the home page course api and then i have

the slides page where i have the slides

and if you take a look if you click on

it notice all the useful data that we

get over here so for example this is

going to be our request url which is

going to be again course api.com so that

tells me well what the browser is trying

to get

then check it out the method why it's

get because that is default in the

browsers every time you open up the

browser and search something then of

course you'll be performing a get

request now check out this one the

status code it is 200 why because

everything is successful because servers

send back the data then we have this

remote address and basically that is the

ip address for my server as well as

notice this colon 443

and we'll come back to this one when we

set up our own server because if you

remember we were always setting up the

5000 so you're probably wondering well

what is this 443 and don't worry again

we'll cover that one once we set up our

first server

and then again we have response headers

for example and we also have the request

adders so as you can see using this

network tab we can actually find a bunch

of useful information now

notice here in the second set of tabs i

can see this response and preview so if

you take a look at the preview

this is going to be basically my site

and also i can see the response so as

you can see pretty much sending back the

html

so i'm sending back the website so you

go into the browser you request a

resource

by default it is a get request

and then in that body

when the server sends it back

this is what we get back so we get back

the site so hopefully this gives you a

clear understanding of how the http

messages are structured and now let's

dive into creating our own server

awesome once we're done with the slides

now let's start setting up our server

and in order to follow along with the

course you'll need to have a starter

project and you can get it if you

navigate to my site again the url is

johnsmilk.com

so navigate there in the project or in

home page look for node express tutorial

project in a home page is going to be

at the bottom in latest project if you

cannot find it there then look for all

projects page or simply projects page

then filter for node in order to save

some time and then like i already

previously mentioned any of these links

will get you to the repo and then

bravely get the repo in my case i'm

going to clone it so i'll copy the url

i'll bump up the sound size in my

terminal navigate to the desktop

get clone here

and then i'm gonna get the repo and then

once the project is on my machine

i'm just gonna drag and drop and then

the first thing that i would suggest

doing is removing the remote url and you

can simply do that by just wiping out

the git folder so that way if you ever

do decide you push this up to the github

you won't have some dumb permission

errors so i'm just going to open up the

integrated terminal now in my case i'm

not going to run the command but

if you're on mac i suggest running rm

then hyphen rf and then get now if you

are on windows

some students have just these two

commands now i haven't tested them yet

but some people have replied to

my tweet that yes they do work and if

you want to see the whole tweet just

navigate to my twitter the handle is

john underscore smilga and then as you

can see here is the mac command and for

windows i have these two so run this

command and then in next video

i'll give you a brief overview of the

repo all right and before we get busy

why don't i give you a brief overview of

the ripple

and if you take a look at the first

project this should look very very

familiar because essentially this is all

the code we have written so far

everything starting with our most basic

application and then of course we also

have our last one our http streams

example so hopefully that is clear and

if you ever need to jog your memory

essentially this is just here for your

reference

and then from now on we'll work in a

folder number two by the name of express

tutorial

and the idea is gonna be exactly the

same where basically

we build a bunch of examples and in the

process we learned what is express and

why we would prefer using express

instead of straight up http module but

again let me stress something where

express is built

on top of node and more specifically on

top of http module so it's not like you

can use express without node and in

folder two

the setup is following

where there are gonna be some assets

that i provided

just so we can make more real world

examples so hopefully that gives you a

better idea how the express works and

i'm not going to cover them right now

for example methods public or navbar app

once we get there i'll explain

everything that's happening i think that

it's going to be waste of our time if i

do that right now however if you take a

look at the final folder you'll

basically see

all our examples so the same spiel

if you ever

need to reference the code just navigate

to the final look for the file name and

then of course you'll find the code just

keep in mind that in order to run

this code you'll have to copy and paste

and run it in the app.js why

because in some cases there's going to

be paths and since these files are

located already in the final the paths

won't match

okay hopefully that one is clear as well

and then we also should be familiar with

these files

as you can see i have package.json i

have package.json lock and then app.js

now of course app.js could be renamed

server or whatever you would want but i

already have in a package.json a script

that spins up the nodemon and

effectively we have successfully set up

a node application so package.json is of

course needed because we'll have some

dependencies more specifically two one

is going to be nodemod and the second

one is going to be express

and in order to of course keep track of

those dependencies we have

package.json and then if you notice i

don't have the node modules here and of

course the reason for that is because i

don't want this repo to be massive and

you can clearly see that in a git ignore

where i have node modules included so

when i was pushing this up to the github

and of course

i omitted the node modules since i added

them in the git ignore and then in the

package json like i said

you'll find some dependencies and i'll

talk about express once we get there the

moment let's not worry about it the one

that we should be familiar with is node

one which is going to be watching our

application and i have a script

that sets up nodemon

and passes in the amp.js so any changes

in our project nodemon will be watching

and restarting our application however

we cannot do anything before we install

all dependencies otherwise you'll just

get an error so that's why the first

thing that i would want you to do is

navigate to the folder number two

and the fastest way probably is just

going to be cd and then take the

project number two and drag and drop

like so and then once you can see

that you are in this folder

so not in a root not in node express

course but once you are actually in the

folder number two before you do anything

just run npm

install first and then it's really up to

you you can either wait for all the

dependencies to be installed and then

run npm start or you can simply chain it

and say npm

and once you run this one

then of course you'll install

dependencies and if you see in a

terminal express tutorial that means

that everything is correct and you can

continue with the videos if you don't

see that then please troubleshoot

because none of the things that we're

about to do next are going to make sense

if you're not running the project number

two with all the dependencies more

specifically nodemon and express

and lastly i just want to mention yes

there's also this data.js and again this

is one of the assets that i added that

we're going to use a little bit later so

if you see express tutorial in a console

and the reason why it's there because

that's the only line of code i have in

my app.js that means that everything is

correct and we can move on to our next

topic and why don't we start

the express tutorial part by setting up

the server one more time with

straight up http module

and in a process let's struggle a little

bit

let's see why we would want to use

express e in the first place

so yes we'll build one more time server

with http module however now of course

we'll dive deep into the topics that we

kind of skipped over before

and in order to set up the server we

know that we would need to require the

module right so i'm going to come up

with some kind of variable and in my

case that is going to be http and of

course the name is not required you can

call this whatever you'd want but it is

somewhat off a convention to call this

hdp as far as the variable name then we

go with require and we just go with http

again keep in mind

this comes built in node

so you don't have to install it we

didn't install when we ran npm installed

in last video

we installed two other dependencies but

this one is built in so we don't have to

do anything we just say require and it's

always going to be available to us

then we need to set up the server and

again convention is calling the server

but you can call this box bunny and in

order to do that we go with http and

then on this object we have a method by

the name of create server now this

method

takes a callback which is going to be

invoked every time the user

hits our server and in this callback we

have two parameters and again we can

call them whatever we would want so

again common convention is just shorten

this up a little bit and call it request

and res so rec and res and the first

parameter references the request object

and second one is the response object

and at this point it should be clear why

we have access to those two parameters

because

in the http cycle we have request

message

that is coming in every time user

requests the resource and also we have

the response message right so that's

what we need to send out so that's why

in this function

that runs every time user hits the

server

we have access to rec

and res

so that way we can find info about the

incoming request because it makes a

total sense if we have access to that

info

i do want to know what is the method so

what the user is trying to do i do want

to know what resource the user is trying

to get

whether that is the contact page or

about page and also i would want to know

whether i'm getting some data

whether user is trying to add something

onto the server and as far as the

response well in order to

serve the data

i need to be extremely specific about

what i'm sending so i need to explain to

the browser what is coming in hopefully

that is clear and in here we can just go

with log

and we'll say user hit the

server and then we return the object

from this create server and on that

object we have a method by the name of

listen so in order for the server to

work we need to invoke listen and we

need to be a bit more specific and we

need to say well what port are we

listening for and you're probably

wondering well what's up with this port

what's up with this 5000 value

and the best explanation i can give you

is this one imagine scenario where you

have some kind of issue with your bank

what do you do or that could be a phone

company it doesn't really matter but i'm

just going to give you a bank example

what do you do you call the customer

service and what is the first question

that they ask you

they say

please describe your issue

so we may better assist with your call

and what do they do they give you

options right so they say if you want to

increase your credit limit this is going

to be option number one all the way to

canceling the account which maybe is

going to be option number eight so they

don't just randomly assist you a person

they say hey what is the issue

and this is the person that can serve

you the best so if you press 8

you can assume that you're probably

going to be speaking with someone who

deals with that all the time

and same goes here so if you go online

and if you search for port this is just

going to be a communication endpoint

and we need to understand that for http

traffic we have specific ports

so for http we actually have port 80

because there's other ports as well if

you keep on scrolling here and by the

way this is wikipedia example we have

port 20 which is for

file transfer protocol so this is going

to be for data transfer then we have

port 22

for secure shell so http traffic

is only one of the things

that we set up on a server and once our

application is in deployment we have

specific ports for that we have 80

that is going to be for just http and we

also have 443 which is going to be 40

secure communication that's why

when you go to course api or any other

website that uses https you'll notice

that

there is a ip address and then more

specifically 443 and you can also think

of this as a apartment building

so every apartment building has the same

exact address right but the apartments

differ

so the same works here so on that server

if i want to access it using ssh so

secure shell i'm going to use

port 22 but then if for example

i want to use http protocol and if i

want to access resource that way then

i'm going to use port 443 so once your

server is already in production yes

these ports are not random there are

specific ports for specific things we

would want to do again back to our bank

example if i want to cancel the account

then i'm always going to be directed to

that person because i'm going to click

option number eight if i want to

increase the limit then of course i'm

going to be directed to a different

person now while we're in development

this is really arbitrary

i can go here with five thousand i can

go here with three thousand eight

thousand wherever you would want i

believe the ports between zero and

thousand twenty four

are already taken so you shouldn't be

using them but in local development

again this is an arbitrary number and

that's why you can use anything you

would want

and again the most common example create

react app where we spin up the server on

localhost 3000 then gatsby has i believe

eight thousand and then netlify cli has

8080 and i can go on and on and on so in

my case i just went with 5000 but if you

don't like this number just use a

different port but of course please

remember the actual value for the port

because you'll need it once you need to

access now if you're wondering well what

happens once we deploy our application

just put the pin on that and once we get

to deployment of course i'm going to

cover how actually we set it up that we

serve that traffic

on the

port 80 for example for http or 443 for

https

and now of course we can go and test it

out so let me navigate to my browser

and i'm just going to go with localhost

and eight thousand and or i'm sorry i

just said five thousand and for some

reason i went to eight which is gonna be

the gatsby one and you'll see this

interesting spinner

so what's happening over here well the

thing is yeah the user hit the server as

you can see user hit the server that is

what i see in the terminal however

remember

we have the response right so we have

access to the response object and now we

need to send back some info to the

browser otherwise the browser is like

okay

so i hit this resource but nothing is

happening

and there's a method that we always

always need to include

in our response and the method name is

and and i right away went to node docs

of course again if you want to navigate

there yourself please do so but i

already right away went for response dot

end and as you can see this method

signals to the server that all the

response headers and body have been sent

and as a side note we'll do the headers

in the next video because this one is

already getting quite long

that server should consider this message

complete the method response and

must be called on each response

so

for the browser not to be confused we

need to go with res that end so res dot

and that is one of the methods that is

available on this response object and

here we can either pass the text or we

can set up for example html and in this

case i'm just going to say home page

that's it i'll just pass in the string

and if we were to go back to localhost

5000 there it is now we have our

homepage response and we can clearly see

that in our terminal because every time

you refresh the browser you'll have this

console log in a terminal user hit the

service

hopefully everything is clear again we

have access to http module and that is

built in node and we just set it up some

kind of variable most common convention

is calling this http then on there we

have create server method that takes in

the callback which is going to be

invoked every time the user hits the

server and as parameters we have a

request

and response object and common

convention

is just calling the american res now of

course you can call this stockhold

burrito if you want but again common

convention is calling this iraq and res

and the reason why we have access to

those objects

is because in the http cycle

that's what happens we have a request

message that is coming in where we can

find a bunch of useful info about the

request that is coming in and then of

course we need to respond to the browser

in a meaningful manner so that's why we

also have the response object and in

every response we should always have end

which is going to signal that the

communication is over and then we just

need to set up the port and again in

development we just come up with

arbitrary numbers and in my case we go

with 5000 and we pass in that port

in the dot listen method which is

available when we invoke create server

because we get back the object hopefully

the basics are clear and now we can

start expanding on our knowledge all

right we're done with the basics but

there are two major issues with our

current setup first of all we don't

provide any info about the data that

we're sending back

so we don't have any metadata about the

body that we're sending out so we're not

providing any information we just go

rest that end and then pass in the

string so that's issue number one and

then issue number two

if i were to go

to the local host 5000 and if i type

about

or if i type contact or whatever you'll

see that of course we're sending back

the same response each and every time so

if we go with contact again this is

going to be a home page so why don't we

deal with issue number one first

where we provide more info to the

browser of what we're actually sending

back

and then in the next video we'll deal

with the request

and the way we provide more info we just

need to add

more methods now specifically one more

method and that is going to be res dot

write head

and in there you can probably already

guess that we're just providing headers

so we're providing metadata about our

response and we go here with res dot

and then we go with right

head so right head and then we need to

provide a few things we start with a

status code and i'll talk about the

status code in a second and for time

being i'll just pass in 200 which just

means that the request was successful

and then we pass in the headers

and one of the most common headers is

the content type

so this is where i specifically say to

the browser hey listen i'm sending back

html or i'm sending back css so where

i'm sending back the image so browser

knows

well what to do how to render that

content and like i mentioned already

previously this is done using key value

pairs so we go with content type so

that's the name of the header and then

we pass in text

and then if for example i want to pass

in the html i go with text

forward slash and then html and now of

course in this case where i have the

res.end i can set up the html so for

example i could go with heading 1

and i'll say

homepage same deal home page now if you

want you can keep it this way where you

have res that end and you directly pass

in the html however i like to use better

this approach where i go with res dot

write and we do the same thing we pass

in essentially the body and i set up my

html here in the right or any content

that i'm sending back and then

explicitly call res.n again if you want

you can pass this heading 1 into the end

just make sure that you have the end and

you saw that in a docs where it says if

data is specified in a similar effect to

calling response.write and then we pass

in the data followed by res.n but you

always always need to call res.n so this

is really up to you if you want you can

pass this directly into res.n

i like to write it a bit explicitly

where i say res.right so that is my body

and then i just end the communication by

calling

res.n and now of course

if i go back to the browser again i'll

still have the same issue where it's

going to be displayed for every request

meaning either contact page homepage or

whatever but now i provide way more

useful info to the browser where browser

knows hey i'm getting back the html so

i'll need to render html

and this stuff matters so let me show

you if i change the content type back

for example to plain

and if i save and if you refresh now

notice this is now treated as a text

it's not treated as html so whatever you

set up over here in the content type yes

it does matter now express takes care of

that so we won't have to do that but i

just want to let you know that if you

will be setting up the headers yourself

yes the stuff that you type here matters

and as the note it is also called mime

type or you can think of it as media

type so whatever we're sending back and

now let's go over the status codes as

well as other options for mime types and

this is where i would like to introduce

an awesome resource for anything http

related and that is going to be no other

than the mozilla docs so if you go to

http and status codes you'll see

probably the first link is going to be

to the mdn

and as you can see http response status

codes indicate whether specific http

request has been successfully completed

and like i mentioned before there are

quite a few groups over here and there

are quite a few codes but i would

strongly discourage you from spending

your weekend on memorizing the codes as

we're going to be progressing with the

course as we're going to be creating

more complex applications of course

we'll introduce more and more status

codes but the main idea is following

where

when we send back the response

i'm just saying is it successful

maybe the resource wasn't available so

then i sent back 404 or maybe there was

a bad request that's why there's also

option 400 and hopefully you get an idea

where we are setting up that status code

so the browser knows what is happening

with the request was it successful

was there an error maybe i don't know

you're not authorized to access it and

on and on and on and if you keep on

scrolling notice so the 100 ones are

going to be informational responses then

for successful one we have 200

so that probably is going to be the one

that you'll use the most so that means

that request has succeeded then we have

201 also something that we'll use

throughout the course a lot and this one

is

once the post request is successful so

if you add the resource successfully

onto the server then you just send back

to one

we have 300s for redirect and then these

are the ones that you probably don't

want to get

if you are surfing the web so 400 is for

bad requests

so for example you are requesting some

kind of data or you're trying to do

something on the server but you don't

provide the info

so i don't know i'm trying to add the

user but i don't provide the username

something along those lines then 401 is

for unauthorized then 403 forbidden and

404 not found so in our case we'll set

up a response if the user is trying to

access the resource that does not exist

so hopefully it is clear that is the

status code again

i wouldn't suggest memorizing it as we

are moving along with the course of

course we'll cover more status codes

just understand the main idea

where you attach that status code to let

the browser know hey what's happening

and it is very important that you use

the correct status codes because

we are in charge here nothing stops me

from sending back the 404 here meaning

the resource is not found

and then when you

navigate to the contact page for example

here and if you inspect again the

browser network tab you'll see this

confusion info where 404

is technically not found

right but at the same time we are

sending back the correct resource so yes

whatever we type as far as the status

code it does matter it's not just some

random info and that just reflects what

is happening with the request and then

lastly let's talk about mime types same

deal just go to your favorite search

engine and just type mime

and types and again i suggest using the

mdn

and these are just going to be media

types so whatever we're sending back

there's quite a few out there now again

express takes care of that

so we don't need to worry about it but

if you ever need to set it up i don't

suggest memorizing them

the ones that you'll need to use

you'll pretty much be able to google it

right away you can also use the npm

packages so no you don't need to go and

memorize them again just remember the

main idea where you're sending back

something right and you need to describe

to the browser well what are you sending

back

are you sending back the image are you

sending back css are you sending back

the html and as you saw in a previous

example

if you change that mime type if you

change that content type header yes the

browser will interpret that differently

and once we successfully have set up

more proper response now let's start

dealing with the request object

beautiful and with our basic headers in

place now let's deal with the request

object

and like i already previously mentioned

it's just a giant object and if of

course we can slog it

then we'll see it in a terminal so i'm

going to go back to my localhost 5000

and as i said note this is getting quite

busy so i can just remove some of the

tabs and if i just refresh the browser i

should see in a terminal a giant object

so what are we looking for

well let's go back to our slide

and remember the start line

we had a method

so that signals what the user is trying

to do either get the resource post a

resource or whatever and then we have

the url

now in order to save us a little bit of

time i won't cover the methods with http

we'll just deal with the url but we will

cover of course methods once we hit the

express for now i'm just going to assume

that the only thing that the users are

trying to do they just want to get the

resources from our server so that's why

we won't look for the method just keep

in mind that yes of course those methods

are available on this request object

there is a property by the name of i

believe it was just simply a method so

if we cancel log

and if i refresh notice here in a

terminal it says get

so the user is performing a get request

so the user is trying to get the

resource so that's one thing that we

could take a look at and the other one

is actually the url so let me uncomment

this one and i'm looking for the url

property

and again i refresh and now in the

console i should have this

forward slash contact so that just means

that the user is trying to access the

resource by the name of contact and if

of course the resource is there awesome

we send something back if not then most

likely would send back the 404 now if i

delete that contact and if i simply go

with 5000 notice i'm going to have the

forward slash so again this just signals

that we're getting the home page so

forward slash is going to be the home

page and then whatever other resource we

would want we would have port slash and

then the resource now sometimes those

resources are going to be forward slash

resource name and then another forward

slash and another resource name and on

and on and on you can really type here

whatever you want so again i go with

localhost about and then info and i

don't know something john right so i can

add that here and there it is now i'm

requesting this resource and if it's not

there we send back 404 if it's there

then of course we send back the useful

info

so hopefully that is clear yes this will

just mean that it is a homepage and

whatever comes after the homepage well

that's the resource that the user is

trying to access and now of course we

can set up the if statement whereas say

yes if it is a home page please send

back

this html if it is about page then send

something else and then if

i cannot find that resource that you're

looking for then we'll send back 404.

now there's going to be a little bit of

copy and pasting just so we can save a

little bit of time we're just going to

go with if and actually we can set this

up as a property so let's go to const

url is equal to request url and then

we'll say if url is equal to forward

slash what does that mean well that

means that it is a homepage so let's

grab these three lines of code

and move them up and now of course i

want to set up else if

now i'll just set up one for the about

page so if url is equal to about page

then we'll do something else and if

none of those match well then i'll just

say

else and i'll send back 404 now i will

add some comments here

just so

we are clear on what is happening so

this is going to be about page

then this is going to be called

home page

home page

and then we're going to have the 404 so

resource not found

so again in order to save us a little

bit of time let's just copy and paste

one and two and again content type will

be exactly the same so that is going to

be html because we'll send back the html

i'll say about

and i don't know page let's call that

and then last one is going to be the 404

so in here of course we're not going to

send back 200. 200 is for successful

request

now of course i want to say hey listen

the resource that you're trying to

access well it doesn't exist on my

server so here i go with 404 and again i

go with the same content type text html

and then let's just send back the

heading 1 with page

not found so save this one

and now of course once i refresh check

it out i get this page not found why

well because there is no resource

forward slash about info and john

but if i go to just about

there it is now of course i have my

about page and then if i go back to the

homepage of course i have heading 1 with

a home page now we optionally if we want

we can

add the status text as well and in order

to see that let's just go back to the

node docs so this is going to be the

http

and of course i'm looking for right head

and we have a right head here notice we

have status code optionally we can pass

in status message and then we have the

headers so again let's go back to our

slide

this is the most important one status

code and then the status text

essentially is just going to be added in

this case we don't need to do anything

because again if we were to go back to

the browser network tab

and if we take a look at our localhost

there is first of all this is forward

slash that just means that we're going

to the homepage and the status code is

200 and then we have this status text

now again if i navigate to a page that

doesn't exist for example john then of

course i'm going to get the 404 so

that's the status code and then the

status text is not found

so hopefully it is clear

now we have a bit more

meaningful server where we have

multiple resources we have home page we

have the about page

and also we have the error page and with

this in place now of course we can start

working on more complex setup

nice and with our most basic example in

place now i'm going to start throwing

mine grenades at you first of all i want

to let you know that of course we're not

limited to passing in the html directly

into the dot right or that end meaning

imagine if you would have to every time

just set it up or your html in methods

directly of course what we can do

instead

is set up the file

then require the file using the file

system and then just pass it in now keep

in mind one thing though where we will

be passing in the

contents of the file not the file itself

and that's very important we'll be

passing in the contents of the file so

that means we still need to use this

content type just because we're going to

be getting the data from the html file

doesn't really mean anything

yes it's nice it's going to make our

lives easier if you want to set up a

more meaningful web page but we still

need to set up the content type now this

is going to be a temporary file because

in the next video we'll cover a more

serious example and i already prepared

all the files for you so this is where

we'll really struggle and this is where

i'll show you why we use the express but

for now if you want to follow along

just create a simple

index html or about html doesn't really

matter how you call the file

in the folder again this is really

optional i'm going to go with new file

and i'm gonna call this index html and

again the whole reason why i'm doing

that because i wanna set up a more

proper page and i don't wanna type

everything here in the right or end i

mean it's much more nicer here right so

i'm just going to go with emma setup in

visual studio code i get my basics and i

can say

home page home page

and then i'm just going to go with a

heading 4 of hello world again this is

just a showcase that sky is the limit

just like you normally would set up to

html you can do exactly the same thing

and then i'm going to go back to app.js

and first of all i'm going to get the

read file so i'm gonna go with const and

then read file and sync and i'm gonna

talk about why i'm using this thing in a

second so don't freak out i know i

mentioned before that we need to be

mindful

of the methods that we use

that there is a difference between the

blocking and non-blocking and i'm just

going to go with fs over here

and we need to come up with some kind of

name and again in the next video there's

going to be

more data here so that's why i'll say

get

all files

for time being in this video i'll just

get one and i'm going to call this home

page again

call it whatever you would want you can

call this bobby lee doesn't really

matter it's just a variable and we're

going to go with read file and sync and

of course where's the file it is in the

same folder so we go with relative path

and i'm just going to call this index

html now again we're getting the

contents

now

why i'm using here they read file sync

well there's two reasons first of all we

need to keep in mind that we're not

invoking this

every time someone comes to the server

please keep in mind that we require that

file

when we instantiate our server

so basically that initial time

when the server starts running so it's

not like when the request comes in then

again every time we're requesting the

file yes of course if i were to place

this in the if block yeah that's a

different scenario meaning if i were to

even place this in a create server again

same scenario but not in here again

we're just requesting this once that's

the first reason why i went with that

and second it's just an example so i

want to make my life a little bit easier

what i want to focus on is something

else with this home page in place now of

course what i would want is to go back

to my if where i'm checking for the

homepage and instead of going with

res.right and then typing it out i'm

just going to go with our content now

again we're still keeping this one the

text.html and i'll show you in a second

what happens if we change it to a text

plane and now we go with a homepage

and now be prepared to be amazed because

if i go to not john

my resource of course doesn't exist

there it is check it out we have home

page as well as the hello world

so we can start making some meaningful

html pages and we can serve them with

our awesome server and just to

re-emphasize my point

if we change this to a plane and save

and refresh

now of course we're getting a text so

yes it is very important

of what content type we are setting up

so let's go back to html and now of

course we are in good shape awesome we

have our homepage and now of course i

can go to index.html and go wild and

crazy

with my page setup

not bad not bad now we know that we can

access the contents of the file directly

so of course we can set up proper pages

but now let me throw you a mine grenade

where we'll have to add way more code

here

if we want to really serve some

meaningful web page

and the example is going to be following

if you navigate to navbar app so that's

the folder you'll find index.html

you'll find style css logo svg as well

as browser hyphen app.js and i simply

call this browser app file so you're not

confused between the two so this is

going to be for our server and this is

our browser app and effectively this is

a complete app that we set up i believe

in my javascript course when we were

building projects so effectively this is

a little navbar with a toggle

functionality and let me assure you

something right from the get go the app

works

so if you get any issues along the way

it's because the node is not working

the app itself is going to work and i

can simply showcase that if i go to

navbar app and i'm going to copy that

one and i'll place it

on my desktop

and then if you spin up the index html

i can guarantee you that this is going

to work there it is that's my

application

and i can make it smaller and there it

is now i'm toggling again our goal is

following

i want to take this project index.html

with style css logo as well as the

javascript file

so the html structure

the

styling the logo that you can see over

here as well as the logic i want to take

all of it and serve it on my server

and i know that the app works so all

that is good so let's see what struggles

we're going to have along the way so

here i have the home page right

and instead of getting it from the

index.html which by the way i'm going to

delete because again this was just

temporary now of course i would want to

access this one

from the navbar app that's the folder

name right and then i'm looking for the

index html and i simply just need to

change my path where instead of getting

it index html from the root which

doesn't exist anymore i'm going to go to

navbar hyphen app

and then of course i still get the

homepage

and as you can see i'm still serving

also the contents from that index.html

the only thing i did

is just change the path that's it

and technically we should see exactly

the same right

but

here's the kicker we navigate here and

if i refresh

what is happening

i don't have the logo

i don't have the button

i mean i do have the button but it

doesn't do anything and i can see only

the structure

and we have quite a few 404s here

and actually to give you a good idea why

is this happening

i want to navigate back to our project

and let's just console log

the urls

and i think this is going to give you a

clear message why this is happening so

let me go back and i'm just going to

refresh one more time

and check it out so we're requesting the

homepage so that makes sense right so i

come here i request the home page and i

serve this html file

from the navbar app

and then i have three more requests

i have one for styles one for browser

and one for logo now why is that

happening well because in my index html

if you check it out

of course i do reference the style css

because i want to add the styling right

i do reference the logo

because the logo is right here in my

folder

and also of course i do have the one for

the app right the one where i have my

logic

so this is what happens we send back

the initial

html content and the browser starts

reading the content

and every time we have basically a path

to our server browser is like hey server

give me this resource so give me style

css give me logo svg as well as whatever

we have here the browser app right so

keep in mind that these ones are for

icons

and actually they are external so this

one goes to phantasm that's a little bit

different scenario yes the browser still

performs this request but of course this

is external resource

now these ones are on our server but the

problem is following

are we handling these requests

in our create server

and of course the answer is no we handle

forward slash we handle about and then

for everything else we have this 404

so to answer your question yes

now manually we'll have to request

all the files so lower svg style css as

well as the browser app

assign them to some kind of variable and

set up these paths again this is just an

example if you don't want to follow

along if you just want to see how it's

going to work

just sit back and relax

but in my case i'm going to request

all these resources here

and then set up more else if statements

where if the browser wants to get the

css then of course we'll search css if

the browser wants to have logo then of

course the browser is going to get local

and again if you take a look here in the

elements you'll again see exactly why

because we have our html structure and

then there it is we have style css so

notice how browser is going to http

localhost 5000 forward slash what well

style css right well do we have that

path and again the answer is no so let's

do this way i'm going to copy and paste

and i'm just going to come up with

different names here i'm going to say

home styles

and then the third one i guess is going

to be home image

and then the fourth one will be home

logic so that is going to be my app one

then we'll have to change some files

here as well so i'm looking for styles

css i believe right

that's the file name then i have logo

svg

that's where my logo is sitting so logo

svg and then finally let's just delete

this one as well and call this browser

hyphen app

and js so home styles home image and

logic and like i said yes manually one

by one we'll have to add all these

resources so instead of about page

i'll just call this styles and the value

that i want to check for here is exactly

the same like in my browser so they need

to match so then of course the browser

will get the contents

of the css file in this example so i'm

going to go with styles and then css

now i do want to change right now the

content type because am i sending back

the html of course the answer is no

we're sending back the css so we go text

css now let me say this one more time

please don't zero in on these mime types

if you will ever need them you'll be

able to find them within a matter of

seconds just

type along with me and we're going to be

in good shape now as far as the right

in our body so in our response that

we're sending back are we going to send

back html of course the answer is no now

of course i want to send the styles

right and the variable for that is home

styles so that's where

my content is for the styles css and

once i save check it out

now we are moving along in the right

direction because i do have the styles

so it looks already somewhat decent now

the logo is still missing and there's no

logic because i don't have the app.js or

the logo svg but we are moving in the

right direction so copy and paste and

you can probably already guess that

we'll just repeat over here we'll say if

the url is equal to logo svg and i'll

say

image logo as far as the comment

and we're just going to go with logo

and 3g and as far as the mime type for

this sucker it is image

image forward slash svg and plus

xml like so

and let's go with home

and i believe i named this home and

image like so

and then the last one of course

is going to be our javascript so

let's say here logic

and the resource that i would want to

provide is browser app

js like so

and then

the content type is equal to text

and then javascript

and of course now i would want to send

the home and logic

so let's save this one

and now if i go to my browser

and if i refresh

check it out now of course we have

everything we have the logo as well as

the proper functionality with browser

app and notice how

all our requests are 200 instead of 404

where the previously browser wasn't able

to find those resources and now of

course we are providing them and if we

want to test out the functionality there

it is

now i can just go here and notice how i

can toggle the menu as well and now of

course we'll switch gears and start

working with express because hopefully

it's clear that yes we can

set up our server with just http module

but imagine a scenario where you have a

website with tons of resources

and then of course you need to set up

every single resource in this matter now

i don't know about you

but i would go nuts somewhat quickly

all right and once we have struggled a

bit

now let's make our lives easier by

getting to know express js

express is a minimal and flexible

node.js

web app framework designed to make

developing websites web apps and apis

much faster and easier if i have to be

honest it's almost unfair how easy and

fast it is to spin up the api with the

help of express

and while it's not officially part of

node meaning unlike http module express

is not one of the built-in modules at

this point in time express is pretty

much a standard when creating web

applications with node.js express has

awesome documentation which we will

reference from time to time and you can

find the docs at expressjs.com

again the site is expressjs.com

and as far as the install you simply

need to run the command of npm install

and the package name is express

now they do suggest this hyphen hyphen

save flag

and effectively the reason why they do

that is because in the earlier node

versions

if you did not add this flag

then package wasn't saved to the package

json

meaning when you push this up to the

github the next person who was getting

your project well he or she

did not have the reference for the

package so of course that caused the

errors now currently that issue is fixed

so this is just a good precaution

but technically you shouldn't have any

issues if you don't run the command

again nothing bad is going to happen if

you add this dash save but technically

these days you can skip it so just grab

the command like so

and just navigate back to the project

just keep in mind that of course i

already installed the express

for the express tutorial this is just

for your own project if you want to

install the express if you set up your

own package.json and all that if you

want to install the express just run

this command now one thing that i would

like to mention though is that i'm using

version 4.17

so maybe by the time you're watching

this

they already have a version 5. now at

the moment version 5 is in alpha meaning

they're still testing everything but

maybe by the time you're watching this

this is already stable now if that is

the case when you run npm install on

express of course you'll get the latest

version so your version is not going to

be this 4.17 now i wouldn't worry if

it's for example four point i don't know

24 but if it's five there might be some

breaking changes and at that point you

have two options if that is the case if

the version is already five then you can

either

reference the api docs for yourself

meaning you can take a look at the

methods and all that what the version

five provides or

if you want to use

all the methods and properties that we

use in tutorial simply install the same

version how you can do that well

you just need to go to npm install

express so this stays the same and again

you can remove it you can leave the dash

dash save doesn't really matter and

after express you go with add and four

and then again i'm gonna go with the

same one just keep in mind as long as

you have four you're not gonna have any

issues and then one so this is going to

install express

with this specific version hopefully

everything is clear and now let's get to

know express all right and once we have

covered the express library basics now

of course let's spin the sucker up and

see how we can make a server

way easier and with way less headache

and i'm going to start by removing all

the code in my app.js just keep in mind

that if you ever need a reference

go to the final one and then of course

http basics is going to be where we set

up the basic http server and then for

example

the http app example is going to be in

the file number two

and the way we work with express

we start by setting up some kind of

variable and of course we'll have to use

the require so we go with require and

then we're looking for express library

again we can do that because we have

installed the library

but if you haven't then of course you'll

get the error keep that in mind and then

we go with const and then app is equal

to express to whatever we imported and

then we invoke it now

if you're a bit iffy about this syntax

just keep in mind that it is very

similar to our previous example where we

went with http

then created the server and

as a result we had our

server instance correct so this is

similar we're getting a function back

from express and we just invoke it and

we right away have our server instance

with bunch of cool methods now what

you'll also see

on a web is something like this where

since this is a function we can invoke

it right away

and then just call this one app

again

this is really your preference but

mostly you'll see the first option where

we first import the module and only then

we invoke it

so once we have this setup then of

course we have a object with bunch of

useful methods

now the methods that we'll use the most

are following amp.get and i'll just copy

and paste here

and i'll just change it around a little

bit post

and put

as well as delete

and also there's going to be all

use

and a listen now listen

we already covered before in the http

module and this one is pretty much the

same where we just go with

app.listen and then we just say what

port we're going to be listening on so

in this case of course this is going to

be 5000 and then we pass in the callback

function so when we instantiate that

server we will run this function and a

common convention is just setting up a

console log where we say that yeah the

server is listening on port such and

such now for time being we're hard

coding this value later i'll show you

how we can make this one dynamic so for

now i'll just say console log and then

server

is listening

on port and then we go 5 000. so let's

save this one and i'll run my npm start

and i should see in a console server is

running or listening on port 5000

awesome so what about the other methods

and the first four methods here just

represent http verbs

now if you remember

when we talked about the http request

and response messages

well one of the things that we're

looking for in the request message was

the http verb

and yes

i set up some more meaningful examples

where we'll see all of them in action

for now just remember two things first

this just represents

what the user is trying to do

whether read the data insert data update

data or delete data

and by default all browsers perform

a get request

so that's why we have here amp.get that

post put and delete now all

just works with all of them and we'll

see that in a second when we set up the

404 page so essentially a response if we

cannot find the resource on a server and

app.use is responsible for middleware

and since it's such a crucial part of

express of course i prepared more

examples on that where we cover

everything from the scratch so for now

just remember this is middleware but

don't lose your sleep over it we'll

cover it a little bit later in the

course so we have app.listen beautiful

we're listening on port 5000 but since i

know that all the browsers are

performing a get request i simply go

with app dot get

and then i need to specifically add two

things a path so what resource the user

is trying to access and it would make

sense if we would start with root

correct and then the second thing

is the callback function so this

callback function will be invoked every

time

user is performing a get request

on our route so basically on our domain

and then this callback function gets the

same two arguments we go with request

as well as the response so this is going

to deal with incoming request message

and then this is going to deal with our

response and in express we go with res

and then the method name is send so in

here we can pass the string we can pass

in the html and i'm just going to simply

start with home

and page so we save this one

and now of course i'm going to navigate

to my browser i'm going to say localhost

and then 5000 and there it is now we

should

have homepage if you don't again please

troubleshoot because otherwise it's not

going to make sense

what we are about to do next but if you

see the home page you are in good shape

so we're listening for get request on

our route and then every time the user

navigates to the root then of course we

just send back the homepage now if you

want you can of course go to log

and user hit

the resource or something like that

doesn't really matter and then if you go

back to the browser and if you refresh

there it is we have user hit the

resource awesome

and just like in our previous example

the basics one let's set up the about

page as well as the 404

so i'm going to go back to my app js

and right above the app that listen i'm

going to go with another app that get

and in this case i'm looking for about

so that's the resource and of course in

here again we have rec and res

and then as far as the response well

i'll cheat a little bit and i'll just

say res.send

and we're going to go with about page

and then of course i would want to

handle the 404 as well

so if the user

comes to my server and tries to access a

resource that doesn't exist well what am

i going to send back

and we can take a look at the default

one so if i'm going to go with about i

should

see the about page but if i go with for

example a contact page let's see what

the express is doing and in this case i

have cannot get the contact and if i

inspect i can clearly see

that in my network tab i have contact

and this is a404 so that's going to be

the default response now

i can alter this of course and i can set

up my own 404 response so i'm going to

go with app and this is the case where

i'm going to use all methods because

again

user can do multiple things on a server

and i want to cover them all

not just getting the resource or

inserting the resource or whatever i

want to cover them all so that's why i'm

going to use my own method again this

just handles all http verbs whether get

post or whatever and again this method

takes two arguments first one is going

to be the path and the second one is

going to be a callback function and as

far as the path i can say all of them

so whatever resource you're trying to

access the response is going to be

exactly the same if i cannot find the

resource

then i'll just send back this response

so again i have a callback function rec

and res in here and then we're going to

go with res dot send and just like in

our http example i'm gonna go with

heading one

and we'll say resource

not found

and let's close the heading one but of

course i also would want to add the

status right so that would make sense i

don't want to send back 200. that would

be very confusing

so before we invoke send method i can

also add status here and as you can see

i can chain it so i have res not status

so this is where i'll pass in my status

code and then i go with send so in our

not found example of course i would want

to pass in the status code of 404 that

is going to be more correct and the same

goes here technically we can rely on

express

and it does a decent job of adding those

status codes but a more common approach

is explicitly setting up the status code

so that way you have more control of

what is sent back to the browser so in

here i go with res and that send but

before i set up that method

i

set up a status one first and i go with

200 so this just means that the request

was successful so similarly i'll do that

in the about where i go with status we

pass in the 200 and then we set up a

chained send so now if i go back to my

browser and if i refresh now of course i

have resource not found that is my

heading 1 and i can clearly see my 404

and if for example i'm looking for about

there it is i have my about page as well

as the homepage so if we go to localhost

and 5000 that's going to be our route

that is going to be our homepage all

right and we're done with our basic

example hopefully you can see that it is

already way less code

than just using the built-in http module

and in the next example you'll see how

express truly shines when it comes to

setting up a server beautiful we're done

with our basic example now let's tackle

the big beast our navbar app

and the setup for the following examples

is really up to you if you're not a fan

of retyping

something you have already learned you

don't have to do that you can just

remove app.get

all the way to app.all so basically

leave the import as well as

instantiation and

listen as well however i am a fan

of

repeating something because that way

whenever i need to create something from

scratch i already have done it quite a

few times so i don't have that blank

page syndrome where you're like looking

at the empty file and you don't know

what to do so in my case i'm going to

remove everything and we'll start from

the scratch so const express is equal to

require and of course we're looking for

express

and then i'm going to set up my app that

is equal to express we invoke it and

again we go with app.listen

and we're going to go with 5000. now i'm

not saying that i'm going to do that for

every example

but i'm just showcasing what is in my

approach when i'm starting something new

so when i'm learning something new yes i

do like to retype some of the stuff

quite a few times because

that just makes sure that i remember it

better and in here i'm going to go with

server here's listening

on port and we go with

5000 and then dot and in order to set

everything up we're going to go with

app.get so again i'm looking for the

root and of course i would want to start

with my index html correct that's the

start

and we go with app.get so we're

listening for all the incoming requests

that go to our route

and of course we're specifically

listening for get requests then we have

our callback function rack and res

and we'll set up the functionality in a

second before we do anything let's also

set up all

and this is of course going to be for

all the requests

that will hit 404 so we're going to go

with rack and res

and here let's say res and then status

so let's add here a 200 or i'm sorry

four four my bad and then we're gonna go

with send

and instead of the send let's just go

with the resource

not found

now when it comes to get

in this case i would want to send the

file more specifically i would want to

send back the index.html

and in order to do that i need to use

send file method that comes with express

now in there though i do need to provide

a absolute path so we'll have to use one

of the modules we covered before and

that is going to be a path module so i

go with const path is equal to require

and i'm looking for path module again we

don't have to install it comes

preinstalled with node so we are in good

shape and then where we have our

callback function we go with res

and send file method and here let's pass

in path and then resolve so path dot

resolve remember that was one of the

methods we cover

and effectively i would want to pass in

the dirt name

so this is going to be path to our

directory because we do need to provide

that absolute path and then of course

we're looking for our index.html which

is sitting in the navbar app so forward

slash and then navbar

hyphen app and then we have another

forward slash index html now if i have

to be perfectly honest in this case we

can also use path dot join it doesn't

really matter since their name provides

that absolute path but just to be a bit

explicit that we are providing

absolute path i went with path dot

resolve and then the their name and then

whatever is the path to my index html

and the moment we save it

we'll have the same errors

just like in the http module so i go to

my localhost 5000 and i still have the

same issues i still don't have style css

there's no sign of browser app as well

as the logo

now in express though we don't have to

do this whole song and dance

like in http module

in express i can simply go above all my

app.gets and amp.alls and i can go with

app

dot use and this is going to be the case

where i'll type out the code and then

i'll explain everything that is

happening and we'll pass in the express

so

this is what we're importing so this is

not going to be our server instance

instead we're going to go with express

and then static that's the method and in

here again we just need to provide a

path now common name is setting this up

as the folder by the name of public

please keep in mind technically you

don't have to do that you can just point

to our navbar app but in my case i will

do that i will set up here

dot forward slash and i'll call this

public so now of course what i need is

to set up a folder by the name of public

and then

all my static resources all my static

files i would want to transfer there now

don't worry about it i'll cover in

length

what in a server land means static

resources for now what i would want you

to do is go back to our folder

and that is going to be express tutorial

and of course you can do that in visual

studio code i just think that this is

going to be a bit easier to see so i'm

going to create a new folder again

common convention is calling this public

but you can call it whatever lobster it

doesn't really matter and then in my

case i'm just going to copy these files

so take browser app take logo and take

styles if you want you can move them

just remember that the previous code is

not going to work as far as the http

module setup so i'm going to copy these

ones

and paste it here in my public so now of

course i have browser app logo svg and

style css

so

of course now i can zoom out and once i

save

check it out

when we navigate to our route there it

is this is our application and what's

really cool all those resources are

right away available so if i go to my

localhost 5000 remember browser was

looking for what well it was looking for

example for style css if you go here

there is a resource by the name of style

css and of course in here i have all my

css code and notice how

we didn't have to set up the statuses we

didn't have to set up the content types

or any of that express takes care of it

all now of course you probably at this

point have more questions than answers

so let me start clearing them up and

first i'm just going to add a comment of

setup

static

and middleware middleware

and like i mentioned app.use is for

setting up the middleware and we have

more serious examples coming up

so for time being please don't worry

about this line okay so please don't

worry about app.use what is express

static that is essentially a built in

middleware i will cover everything step

by step

in this video i would want you to

understand what the term static asset

means

and it simply means

that it is a file that server doesn't

have to change it so instead of our http

example where we created a path

for every such resource

and if i were to have i don't know 20

000 images

i would have to repeat the same steps

instead since this is a static asset

meaning an asset where the server

doesn't need to change it we simply

place it in designated

folder again the common name for those

folders are public or static

and then we just dump all those assets

in there so if i were to have i don't

know 20 000 extra images in here i can

just dump them

and express will take care of it all it

will set up the paths it will set up the

mime types it will set up the status

codes and all of that good stuff so

hopefully that is clear static assets

are just files that server doesn't have

to change and an example of a static

asset is an image file here's the style

file and also a javascript file and here

comes the next question

what is this guy with weird eastern

european accent talking about

because all my life i've been told

that the javascript

makes my apps dynamic

it adds all the functionality

so how come this is just another static

asset

and to answer your question yeah you're

right javascript

does make

our apps dynamic however think about it

this is a browser app so it makes

dynamic on a browser

as far as servers is concerned

it is just a asset doesn't need to

change

now if you're wondering well how to set

up something dynamic

just please put the pin on that and

we're going to cover that when we cover

server-side rendering because there is

such thing as template engines

and the simplest way for me to explain

that is imagine the scenario where you

can actually log in

or in other way just showcase whoever is

visiting the site and then dynamically i

would display for example name

so if the peter logs in then i'm sending

back the html with the text of hi peter

now if the john logs in then of course

i'm sending back the username with the

value of john so hopefully you get the

gist where in this case notice this is

just

same old index html that i'm sending

back regardless of who is visiting the

site but yes there's also an option of

setting this dynamically where depending

on who's visiting the site or what the

user is trying to do i'm actually

modifying my file before i'm sending it

back so hopefully it is clear how much

easier it is to work with express

where if we have static assets we just

set up designated folder and just dump

them all in and static asset just means

a file that server doesn't need to

change

and of course we can start working on

our next example nice hopefully we are

clear on static acids and before we

cover more complex expressed topics i

would want to throw a mine grenade at

attribute

and it goes something like this

so if we put two and two together

i talked about static assets in the

previous video

but if we're looking at the

index.html

isn't this a static asset as well

and of course the answer is yes

so instead of sending this file

we can add it to static assets and we're

going to be in good shape and if i have

to be perfectly honest with you when it

comes to

send file

if we're using it to send back for

example index html

actually we use other two methods

instead so first i'll show you the first

one where we just dump everything

as far as the static assets so i'll just

add index.html to all my static assets

in the public

and that will effectively do exactly the

same like we're doing here with send

file and the other one is going to be

using templating engine so of course

that one will cover when we go to server

set rendering so i'm just trying to

showcase that yes there is this option

of send file and we might use it from

time to time throughout the course but

not for sending back index html files so

first let me just say that the other

option one of the two other options that

we'll use the most throughout the course

is just

adding two

static

assets

like so and then the second one is going

to be server side rendering

where basically we'll use template

engine for that

so in order to set everything up now of

course i just need to take my index html

and again if you want you can just move

it

or in my case i'm just going to copy and

paste

so again i'm going to go back to my

folder

i'll zoom in massively

so you can see better so express

tutorial

there is my navbar app and i'll just

take the index.html

and i'll copy and paste and now it is in

the public

so what happens index.html

is always going to be a root

so

when the user hits the server by default

server will serve this index.html and

since our index.html basically has all

the paths to browser app to logo svg and

all that

we're going to be in good shape more

effectively we don't even need to set up

this send file option

so now of course i can just save it and

once i refresh notice how nothing

changed i'm still serving my app

so we're still in good shape and if you

take a look at the network tab notice

everything still works correctly i'm

still getting all the css all the

browser javascript functionality as well

as the logo and to answer your question

yes that is effectively how you can set

up the simple sites you can simply just

dump all your files in the public just

make sure that you serve them up

and that's it and you're in good shape

now we still have the 404 but as far as

just serving straight up sites with html

css and javascript yes you can simply

dump them into public you can simply set

up the middleware and serve all the

static assets and you're going to be in

good shape beautiful we are successfully

done with the initial express setup

and ready to cover more complex express

topics before we do that though

there's something important i want to

mention you see when it comes to express

in most cases you'll use one of the two

following options

you'll use it to set up api

or templates with server side rendering

now since term api is probably one of

the most overused terms in the community

and in various scenarios it can mean

different things let's start by

understanding that in express

or in http case

when we talk about api we mean setting

up an http interface

to interact with our data

now data is sent using json which stands

for javascript object notation and in

order to send back our response we're

going to use

res.json method which will do all the

heavy lifting like for example setting

up the proper content type and stringify

our data

the other flavor we have is server side

rendering where we will set up templates

and send back entire html and css and

javascript ourselves

and we're going to do that using

res.render method

now since i'm a big believer in actual

examples over slides if you are a bit

iffy on either of these flavors just

hold on a bit and once we cover some

examples i promise you it will all make

sense

now why am i telling you all of this you

see when it comes to more complex

express topics it only makes sense if we

cover them properly using one of these

flavors instead of just bunch of random

examples

and the option i picked is the api one

so in the following examples we're going

to construct api response using more

advanced express setups the reason why i

picked apr route is because i believe it

lets us focus more on the actual express

since templates by themselves add a bit

more unnecessary overhead especially

while we're just starting out with

express with that said let me be very

clear if you grasp the concepts with api

so using the api flavor you'll have no

problem implementing them with templates

as well since for the most part express

concept setup is exactly the same

we'll cover server side rendering later

in the course so you'll have to wait a

bit for the actual example and since

we're going to start with api let me

just stress the main point one more time

and how it looks like in a real world

so like i said the main idea with apis

is that our server provides data

and what that means that any front-end

app that wants to access it and use it

can simply perform a http request

and using our data set up the api and

functionality how does that look like in

a real world well if you navigate again

back to course api and of course not the

slides slides are just images but if you

take a look at any of these examples

you'll notice something interesting

where we're sending back the json and

you can clearly see that if you go again

to your browser's network tab and here

again let's refresh

and you'll see that this is our response

react tabs project so again the full url

is course api.com and then react tabs

project

and if we take a closer look we can see

that this is the response that we're

sending so we're sending back a

json data and i can clearly see that in

my headers so in response headers as you

can see content type is application json

now where is this data used if you took

either my react course or the vanilla

javascript course you know that in the

course

we build quite a few projects where we

practice data fetching either using

vanilla jazz or react and in some

examples we use external apis and in sum

we use the apis that are here in the

course api so for example with this

react tabs project if you navigate to

react project nutlify.app

and keep on scrolling keep on scrolling

you'll hit the tabs project and here

this is the app that we build

using the data so again on a server

i set up my data i set up the api and i

share the data so i create the http

interface and then the frontend app just

simply grabs this data and again if you

want you can check it out here if you

refresh

notice this request request goes to

course api react tabs project so we grab

the data on a front end and then we set

up the functionality as well as user

interface hopefully this is clear from

now on we are going to be responsible

for sending back the data so now since

we're setting up the server

it's not going to be our responsibility

to do something with it like we were

doing on a front-end in this case we are

responsible for setting up the responses

so we're going to be setting up apis

that our http interfaces to interact

with our data

not bad not bad i think we clearly

covered our two options so one is

sending back the json data and the

second one is server set

so why don't we start by covering the

most basic

json response

and here's what i'm trying to mimic

if you go to course api

and then if you look for the tours

project

you'll hook the url of course and here

you can see that we're getting back a

json data it is an array and each object

represents a tor and if you took my

react course you know that we were

practicing data fetching in react

and effectively we hit this url

and we got the data we got our json data

back and then we built an app

using that data

but again the whole point here is

following where it doesn't have to be

react

it can be

vanilla javascript application it can be

swelled framework it can be

any setup where you're able to fetch

that data

so in here on the server we just share

the json

so in this case of course that is stores

and then anywhere

anyone who wants to access this data

they can just access it and build

something using that data and that's why

it is so so powerful

and

essentially this is what we're going to

do we're just going to send back first

a most basic array and then we'll see

how we can make this more dynamic please

keep in mind two things first of course

eventually we'll use database for that

and of course i will mention that

probably 20 000 times as we're building

these examples

and the second thing that i would like

you to understand that when it comes to

express basics so essentially how we set

up the server

it doesn't really matter

whether we're using server side or

whether we're using json again

if we understand the principles we'll

have no problem

using any of those options so first what

i would want is to navigate back to my

project and again this is going to be

the time where i do write everything

from scratch but then starting with next

example i'll just use some options that

we already covered so for now

yes i'll remove everything and again

we'll set up express

one last time so we're gonna go with

express require

and express okay awesome then const app

is equal to require or i'm sorry not

require we need to invoke the express

like so and then let's go with

app.listen

port 5000

and then let's call our callback

function

and then let's go again with console.log

and server

is listening

on port

on port and of course the port number is

5000. then again i want to set up

app.get because that is the http method

that all browsers perform by default so

i'm going to go with app.get and i'm not

going to go with specific path just keep

in mind that you can and of course we'll

do that later for example i can go here

with api

and then i don't know i can call this

product or whatever for time being let's

just make it simple and we'll just

handle all the root requests so that way

we can save a little bit of typing in

the browser and again we have our

function our callback function rack and

res

and as far as the response we're going

to go with res

and then the method name is json

now

we will go to the docs just so you

understand where i'm getting this

information from

but before we do that let me just tell

you that i might omit here and there the

status one just so we can save a little

bit of typing but don't worry once we go

to some more serious examples of course

we'll still use the statuses because in

my opinion that is just a better

approach where we actually have control

over the status

and as far as documentation if we go

back to express documentation we're

looking for api reference again we are

using

four point something so we are using

version four so make sure you look for

the same one and don't confuse with

express json so this is going to be a

middleware that we pass in effectively

we're looking for response in a docs and

then we're looking for this json option

so res object as the json method and

what happens we send back the json

response and this method sends a

response with correct content type that

is a parameter converted to a json

string using json stringify this

parameter can be any json type including

object array string and blah blah blah

so hopefully you get the gist so the

only thing we need to do is go back and

for example i'll provide an array where

there's going to be two objects and

first one will be named john

and the second one will be susan so

another object

and we'll say name

is equal to susan and we have our most

basic api

so if i go back to my localhost 5000 and

refresh

there it is so now anywhere in the world

i can access this data

and build something using this data now

there's tiny caveat when i say anywhere

in the world there's still going to be

at the moment a course error and i'll

cover that once we actually cover

middleware so again please please please

please be patient we will get there

but hopefully you get the gist where

this serves our data and now we can just

access that data and build

the front-end app using this data now

this default setup is nice

but of course we can do something more

meaningful

where

if you take a look at the folder you'll

notice this data js now what is data.js

it is simply a file with some arrays

and the first array is going to be

products and here as you can see i have

objects and then each of these objects

represents a

single product and all the way in the

bottom we're exporting both arrays we're

exporting products

as well as the people array that we're

going to cover a bit later so now what i

would want to do is import product array

in my address

and then instead of hard coding this

value like so where i just pass in the

array with two objects i'll just dump

the whole products data so let's go with

const we already know how to do that now

since i'm exporting multiple things

since i'm exporting an object i will be

explicit of what i would want so i'm

going to go with

product

and basically i'm destructing right away

i'm going say product is equal to

require and remember

the file is data js like so

and then instead of passing array

directly i can simply go with product

and what do you know when you navigate

to the root there it is now we have more

meaningful json response where actually

this is a product data so on my front

end i can grab it and i can build some

kind of nice front end using this data

now lastly before we go let me just

showcase that of course there's going to

be a content type set up correctly as

well so if you go to network tab and

again if you refresh localhost like so

and take a look now of course what is

the content type

that is application json so now of

course we're correctly getting our json

data so hopefully you have a clear

understanding how to sound json data so

now of course let's make things a bit

more interesting and cover some more

advanced express topics nice once we're

familiar with the most basic json setup

now let's build a more meaningful api

and in a process we'll cover

route parameters as well as query string

parameters and i would want to start in

following way

where essentially i'll leave all this

code but when it comes to my route when

it comes to my home bridge i'll

essentially send back the heading 1

with the link as well and that link will

direct a user to a forward slash api and

then product

and then later we'll cover the params as

well as the query string so let's start

with sending back html instead so i'm

not going with json one and i'm not

gonna send back the file i'll go

directly and i'll say send and here we

have the string of course so i'm gonna

go with heading one

and then home

page

then i'll make sure that i close

because i believe in one of the previous

videos

i believe it was the express

basics

i think i messed it up here notice i

didn't add the closing one so now

everything is correct and now i'm gonna

go with my link

then as far as the href i'm gonna direct

a user to api

and then forward slash

and then of course

i'll also set up a text here so products

and i'll close my link so that should do

it that is my home page and of course if

i go to localhost 5000 there it is i

have my homepage and once i click the

link i navigate to api products now of

course the moment i have the

default response from the express

meaning the default 404 response where

the resource cannot be found and as i

said note if you want to take a look

what response do they send again go to

the network this is going to be very

very useful tab refresh and take a look

at their response so notice the response

that's the html that they send back so

cannot get and then api products now we

already know

why there is this get the http verb

because that's the method that the

browser performs okay awesome so now of

course our job

is to set up a

get request

for this resource so we go with app.get

and i specifically want to handle api

and product so this one just looks a

little bit

more realistic so in here i go with api

and products and keep in mind of course

those values need to match otherwise

you'll get that 404 again i have my

callback function

and now of course i would want to send

back the product however in this case

we'll make it a little bit different

where previously

notice the product we send back pretty

much the whole thing right but

a more realistic approach is following

where when you're requesting a bunch of

data so when you're requesting

collection of the data you're not always

returning everything for that one

specific product and to give you a real

world example again i'm gonna go back to

my react projects and i'm simply using

them because this gives you a visual

representation during the course we

built a e-commerce and then in the

products page notice how we're fetching

the products

but you need to keep in mind one thing

where we're only fetching about the

product the title the price the image

and i believe also the id and only when

i go to that single product page

this is where i get the rest of the data

whether

that is for example a stars the reviews

the description

the availability and all that stuff so

what i'm trying to say is when you're

requesting a collection

of data there's going to be cases where

i simply want to send back some minimal

response so for example again that could

be name image and the pricing scenario

and only if i look for this specific

product

then i send back everything

and in order to mimic that in our

example

in this response

what i'm going to do is i'm just going

to iterate over my product i'll use the

map method and i'll just remove

my description so when i'm sending back

the product it's going to be without a

description so again if we were to send

back everything i would simply go with

response json and then i pass in the

product so again if we go here and if we

refresh now everything is cool

i'm getting my product on the api

product route however

i'm going to make it a bit more

realistic and we're going to go with

const

new product is equal to

product dot map so i'm mapping over and

i'm creating a new array and i'll

reference each item as a product and

then as far as the return well first i

want to structure the properties out of

the product and the reason why i can

access them is because those are the

names that i used when i'm setting it up

so id name image and all that and that

is equal to the product again i'm just

using simple javascript structuring and

then as far as the return whatever i'm

going to return

from

my function

well that is going to be the new value

so now i'm going to go with id name as

well as the image and once i have this

setup in place instead of returning

product

now of course i'm going to go with new

products

and if i go back to my browser there it

is so now i'm getting a collection

but i'm not sending

everything that i know about this

specific item so i'm being selective of

what i'm sending back so yes

there is a resource by the name of api

product and we're sending back the array

but we know that if

the user

wants to access that description he or

she will have to look for a specific

product and in the process we'll cover

what are the url parameters all right so

we're successfully sharing a list of

items so now of course let's take a look

at how we can provide

info

about that one specific product so for

example if i navigate to

product and then forward slash and one

and then i'm going to get only the info

about this first product because it has

the id of one

and

not only i'll get

these three properties but also get the

description

and our initial approach would go

something like this

where yes i see the product okay

beautiful

and we already know how to set up the

route now since i'll delete it

eventually anyway i'm just going to copy

and paste so we can speed this up so i'm

going to go with api products and then

forward slash one

that just means that i'm going to be

looking for

item number one in here

and then instead of map we'll use the

find method

so i'm importing all my products and in

order to get the single product

i'm going to write the following code

where we're going to go with const

single

product and don't worry we will reuse

this code so

it's not like we're just randomly typing

something so let's go with products and

then find now again

i'll reference each product

with a parameter of product

in my callback function and then if the

product id

product id

matches one

because that is my route here

then of course i'll return that single

product so i'm going to say single

product and technically this works

so notice now of course i have only info

about this one specific product and i

have the description however it feels

like using bazooka on a cockroach yeah

it gets the job done but

probably is an overkill

because keep in mind at the moment we

have

only four products so yes

if i really wanted to i could set up

four routes

but what if i have hundred two hundred

three hundred

well that's not gonna work and in

express we have something called route

parameters which essentially is going to

be way better solution

so instead of hard coding this 1 2 3 or

whatever id we want we set up a route

parameter and it's going to look

something like this where i go with my

route and then i have forward slash and

then i go with colon

and then

whatever name out one so think of this

as a placeholder so you can call this

bobby lee you can call this chicken

burrito in my case i'm gonna go with

product

and the id

just to be explicit

of what i'm expecting over here but

again

naming here is really up to you

and what is more important is the fact

how we can access it now if you want you

can actually console log the request

object again this is just going to be a

giant object and for now i'm just going

to leave this one the way it is

so i'm still going to be returning a

product number one and also let's look

for

request

and then we're looking for the params

property so let me count to lock this

one and then again once i navigate back

and if i refresh in the api products

number one

what you'll notice again this giant

request object where we have bunch of

useful properties and methods

and of course i'm not going to cover all

of them right now but similar to http of

course in the express we also have

access to bunch of useful things in that

request object and one of them is the

params so check it out now i have this

product id and the value is one now

please keep in mind one thing that

whatever you're going to be setting up

here in the url as that route parameter

is always going to come back as a string

and this is important in this case

because if you take a look at our data

the id is a number and of course we'll

deal with that in a second

and whatever we set up as far as our

name

is going to be right in here it's going

to be in this request and then

parameters object so now of course what

i could do

is i could just destructure it from the

params

and then use it in order to find that

specific product so that way i don't

have to hard code products number one

product number two and on and on and on

instead i just set up my route parameter

and just come up with whatever name i

would want

just make sure that you add this colon

here

and then we'll access that value and get

a specific product so i'll leave these

two suckers for your reference

just in case you would ever

want to console log them and we'll

simply go with const and the name is

product id

and that is equal to request

that's my request object and params

then i'm going to use this product id to

get my product but remember

it is a string we can clearly see that

and in fact here in the array

well the ids are numbers so if we'll

just try to search it the way it is

of course we won't be able to get our

product so instead what we want is pass

in the number

and then product id now of course if

your ids are set up as strings

which is

somewhat typical setup for the databases

and all that

as well as the headless cms is then of

course you don't need to worry about it

then you can just pass in the string and

now of course i'm going to be able to

get my one product so now if i go back

and if i refresh

everything still works and if i go to my

url and start changing these values

hopefully you can see that now of course

i'm getting a different product now i'm

getting product number two and i go to

product number three and on and on and

on so now with these few simple lines of

code

i can access any product in my array now

of course there's also a case where we

cannot find the product because keep in

mind here i can type whatever i would

want so i can go with products and then

let's imagine that the user types abc

now do we have a product with an id of

abc

of course the answer is no so what's

happening over here now i don't get

anything back right well i don't get

anything back because if i go to log and

then

single product let's see what we're

going to get back again let me refresh

abc and this one is undefined so that's

what we're sending back as a single

product so what would be a solution well

a solution is setting up a if statement

here

where i say get me the single product if

you cannot find that single product if

basically that product doesn't exist if

the id

that the user passed in does not make

sense

you cannot find the product with that id

then return 404 so how's that going to

look like well we can go here if and

then single product so we set up a if

condition and of course i'm going to go

with if single product doesn't exist so

i'm going to add exclamation point and

of course this is going to be our case

with undefined

this will be true if it is undefined and

then we just go with a return

res and in this case i will add a status

because that is extremely important that

i go with 404 and then we go with send

and product

does not

does not

exist like so

now if everything is correct then of

course we go with res

and json so in here i say return

and res dot json so once i go right now

to product and then abc

there it is now of course i have proper

404

product does not exist and if i again

take a look at the tab

and i have my abc now if i'm going to

navigate to a route where i can find the

product then of course i'm going to get

my proper product response so whenever

you think of route parameters think of

them as placeholders where user provides

a data and then using requests and

params we can access that data and then

set up some kind of logic

and before we continue and cover query

string parameters let me just mention

that route parameters can get way more

complex than this so for example imagine

this scenario i can go with app.get

again i need to come up with some kind

of routes i'm going to go with api

then products so i'm looking for

specific products so i'm going to use a

route parameter let's call this product

id

then i'm going to look for all the

reviews and then maybe there's a review

id

so review

and then id and now of course again i

have rec and res like so and then i'm

simply going to send back some kind of

dummy data but i would want to console

log the rec params just so you

understand how everything works and now

let me send

res.send so res

not send and i'm just going to say

simple hello world let's save this one

and again in the browser let's go here

we have products again some kind of id

whether that's abc whether that is a

number in this case it doesn't really

matter since you can see that there's

not much functionality in there but we

need to type in here reviews and then

for example the review id would be i

don't know abc so once i navigate here

of course i'm going to get my hello

world and then in the console notice how

i'm accessing all of them so i have the

product id as well as the review id so

again they can get way more complex than

just this simple approach and one more

thing i would like to mention this

reviews though is hard coded

so if i go back i can change the abc and

4 however i would like but if i'll

change

from reviews to review

i'm going to get a 404 why well because

review is not a route parameter so

that's not a placeholder

so if

this is incorrect then of course i get

d404 hopefully that is clear and now

let's talk about the query string

parameters

all right and once we're familiar with

rot parameters let's talk about the

query string parameters or they're also

called url parameters

and essentially that is a way for us to

send small amounts of information to the

server

using the url

now this information is usually used as

parameters to for example query database

or filter results and that's really up

to the people who are setting up the

server they decide what parameters are

going to be accepted

and what functionality will depend on

those values and to give you a real

world example let me go to my search

engine and i'm just looking for hacker

news algolia api

so when you're working on a front-end

app i'm not sure whether you worked with

this api but that is a very cool api and

essentially it's going to work as a good

example of how we should be setting up

the server and this is as a side note

but

notice the url here

so they go with a domain which in our

case is of course localhost 5000 but

here it is actually a algolia domain so

algolia.com

forward slash api like i said that is a

pretty common practice

then a version number and then whatever

list you're getting so in here it is

items now check out this one

doesn't that ring a bell

of course that is a route parameter

where they say yeah here's the list of

items

but if you want to be more specific

please provide the id

and then if you keep on scrolling you'll

notice the same thing with the users

again we have the main domain

api version one users that's the list

and then if you want to get a specific

one then of course again there is a

route parameter now this is just to

showcase that i'm not randomly coming up

with those things no that's how actually

the servers work in real world and let's

keep on scrolling and now we come to

this interesting part

where we can sort

so

we're getting the data from the algolia

api

but then in my app

i can sort i can say hey you know what

get me specific hacker news story or get

me stories based on some kind of search

term and hopefully you get the gist

where instead of just grabbing the whole

thing

i can say you know what

get me all the stories that match

through so again we go with the url and

this is really up to you how you set

this up in their case they use search

and then

here we have this question mark

and whatever is after this question mark

is not technically part of this url

meaning

it's just a way for us to send that data

to the server and then server decides

what to do with this data

so the url is still this one

the one that ends with search and then

we have a question mark and basically

this is just a specific info

about the data that i'm requesting so

here the user adds a query parameter and

then the value is full and then also has

tags of story and that means that we're

going to get all the stories matching

full now what else you could set up here

in a query string pretty much anything a

pretty typical is going to be page for

example if you have a list of things and

i don't want to get 100 items at a time

i can say you know what split it up in

pages and get me initially page number

one and then only if the user clicks on

a button that fetches the page number

two then i get the second page then for

example in here they have hits per page

so that is going to be how many items

per page so again

after that question mark if the setup is

supported by the server

then of course you can add those key

value pairs and the way we add them as

you can see is by using key value pairs

so we have question mark and then we

have a key

which in this case is query and then the

value now

before we continue let me make something

very very clear it's not like you can

randomly search the web and just start

adding these query string parameters and

then expect

that as a miracle you'll just get the

data that you're looking for a as far as

the keys

they're designed on a server so if i'll

set up a key of chocolate milkshake

algolia api is going to be like i don't

know what you're talking about and the

same goes for the value so where i'm

going with this now we are in charge of

that server so it's up to us to handle

those query string parameters

and i'm going to go back to our project

and i'll purposely set up a new route

please keep in mind one thing where a

pretty typical setup

is adding this to the list

so again we'll look for specific

property on our request object and then

if that property is provided then of

course we return a more detailed

response meaning there's maybe some

filtering or something like that but if

not then we'll send back all the

products now i'll purposely set up a new

route just so we don't jam all our code

in this one route but then

in the next video probably i'll show you

how we can combine both routes so let's

keep on scrolling so this is going to be

our more complex

params example and let's go with app.get

and again

the route is really up to you i'm going

to go with api now in order to make it

interesting i'm going to add that

version 1 just like the api of algolia

has it and then i'll say query now i

don't need to add question marks nothing

like that i just set up query that is my

route and then i have my callback

function rack and res

now in this callback function in order

to access those query string parameters

i need to go with rec and query so let's

go with console.log and we're going to

look for

request

and not params sorry we're going to go

with query over here and again let's go

with simple hello world just so we can

speed this up and then if i go to the

local host

and more specifically

i'm going to look for

localhost then 5000 then api then

version number one

and then query and then if i add this

question mark i can add as many query

string parameters as i would like so

here i'm going to go with the name that

will be equal to john

then in order to combine them we just

add this ampersand so we're going to go

with name john and then id4 just keep in

mind that you can add as many query

string parameters as you'd want and then

once i navigate there at the moment i'm

just going to get the hello world

so that's my default response from this

url

but in a terminal notice i have name

john and id number four again this is a

string and this is going to be important

in a second but what this allows us to

do is access those parameters and then

based on them do some kind of

functionality now first of all i would

want to change this around a little bit

where i'm not going to be looking for

name or id i'm going to be looking for

search query parameter as well as the

limit so if the user wants to search for

a specific product he or she needs to

provide that search query parameter as

well as limiting

where the user can limit of how many

products they are getting back so let me

navigate back and just to showcase that

so again instead of name i will zoom in

we'll say search

is equal and then whatever i would want

so in this case i'm just going to go

with a so effectively this will return

all the products that start with a and

then the second one is the what that was

the limit right so i'm gonna say limit

and

for now let's just go with two of them

so this will return two products

i'll zoom out and again i have search

and i have limit after you so now of

course let's set up that functionality

and we'll simply start by creating new

instance of those products i'm gonna go

with let and you'll see in a second why

so say sorted

product

and in here we'll use the spread

operator so we imported the product

and now i'm just going to copy the

values so this is going to be my new

array and the reason why i'm using let

because

we will modify

this value a bit now instead of just

cancel logging the query i'll comment

this out and we'll set it up as const

and then again i'm looking for two

specific keys i'm looking for the search

and i'm looking for the limit so if the

user doesn't provide them

well then we'll send back all the

product

so we're gonna go

with query

like so so i can see the search and

limit beautiful

and now

instead of just sending back hello world

i'm going to check

if

the search

is in my query string parameters then i

would want to filter my product so i'm

going to say if and then search like so

and we're going to go with sorted

products since i'm using let i can do

that i'm going to go with sorted product

and then filter method again

straight up javascript again i'll call

this a product

like so and what i would want to return

are the products that start with the

value of my search term so here i can

say return

product

and name so if the product name starts

with now again this is straight up

javascript

and i'll pass in the search if that is

the case that is going to be my value in

stored product and i can right away

check for the limit as well

where i'm going to say if

and then limit

and if it exists

so if the user has provided it again

let's go with sort product

and filter more and in this case i'm

going to use the slice method where i'm

just going to get specific items from

the array so i'm going to start with 0

and then remember we're getting a string

so we need to go with number and then

again we'll pass in the limit let's go

here below both of them and let's just

say res dot and then status and we're

going to go with 200 like so and then a

json response

now when it comes to json response we're

just gonna go with our sword product

right so we go back

and let me just showcase something where

if

none of the query string parameters are

provided i'm gonna send back my whole

data why well because i copied my

products right both of them were false

both of them were undefined

and as a side note there is a error here

cannot send headers and i'll talk about

it actually in a second that is one of

my

next topics so let me just deal with

this hello world by deleting it and

we're going to be in good shape but i'll

cover why we got this error and what

gotchas you should be aware of so let me

go back again

let's see again we're getting all the

products because the user did not

provide

that specific query string parameter so

if we right now navigate to the url

and i'm gonna start with a limit and if

in the limit i'm gonna say that i'm only

interested in two products

check it out now of course my limit is

two so i only have two products and if

it's three then it's gonna be three and

then four and hopefully you get the gist

where whatever value i provide here in a

limit well i have the functionality for

it now keep in mind again name needs to

match if this is going to be limi

instead of limit again i'm just going to

get back all the products regardless of

what is my value and the same goes for

the value of the query string parameter

if this is limit but for example i

decide to pass in abc

nothing i get empty array why because my

value wasn't what my functionality was

looking for and similarly of course we

can add the search option as well and

i'm purposely showing them one by one so

you don't get confused so let's say

search

and again the functionality is set up

where you need to provide a starting

character so in my case i'm looking only

for the products that start with a and

there it is i have two of them now if i

want a limit i can just add and here

and let's just type limit and i'm only

going to be looking for one product and

if i add this limit one

there it is now i only get one product

now there's also obviously going to be

the case where we return empty array

why well because

i could go with search and look for the

products of b

and unfortunately when it comes to my

product data i don't have products that

start with b so we can handle that

instead of sending back empty array i

could check what is the length of my

array and if for example it is less than

one then i explicitly send back the

response where i say yes the request was

successful

but i couldn't return any product so we

can go with if and then sorted product

if the length

of this array

is less than one

if it is less than one then of course i

can just go with res dot status now this

is one gotcha where

you're not sending back the 404 you're

not saying the url doesn't exist or the

resource doesn't exist

in this case you're trying to

filter the product but

nothing came back so

whatever query string parameters were

provided they didn't yield any results

so you're simply saying status and then

you can go with send and we can go with

no products

products matched

your

search like so so we can go here and

then if we refresh again with the same

ones we have no product match your

search so that is one option you can

send back the string but

a more common one is this one where i'm

going to comment this out for your

reference again and instead you go with

return

and you're going to go with res dot

status and again we have this error in

the

server and again i'll talk about it in

the next video why we have that one so

we're going to go with res dot status

and we pass in the 200 and instead we

send back the json one and in that json

again you can pass the string if you

want but a more common approach is

setting up the object where you

explicitly say that the request was

successful or a failure so you go with

success and that is equal to true and

then again you come up with whatever

name you would want a generic one is

data and then you send back the array

again you are in charge here you can

really do whatever you want i'm just

showing you

a pretty common

approaches to the situation so again i'm

looking for some kind of product

using my query string parameter now

unfortunately server can return

any data meaning

any product and then of course i just

get this success true because the

request was successful there was nothing

wrong with my url however

i'm just yielding a empty data so that's

it i can just delete it and if i don't

provide anything then i'm going to get

all the products hopefully that is clear

how the query string parameters work and

now we can cover a few gotchas all right

and two things that i would like to

emphasize are following first

remember those errors that we're getting

in a server when we're setting up if

conditions

in javascript if we don't explicitly

return

then of course javascript just keeps

reading the code correct so if i'm going

to omit that return i'm actually going

to get the server error where i send

back one response and then javascript

just keeps reading the code and then

express is confused express is like hey

wait a minute i already sent back the

response so while you're sending another

now keep in mind that it is happening in

the same request so you cannot send

basically two responses in the same

request one after the another yeah of

course you can send one based on the

condition so for example if there are no

products you send back one response

and if you can yield some product then

great then you send the second one but

you cannot send both of them

one after another in the same request

and if you want to see that error again

in action go to the query you'll add a

question mark here

and we're going to go with search and

again it is equal to b for example that

is my value that's the starting value

that i'm looking for and once i do that

notice yeah i'm getting back the success

true and data but again i have this big

fat error in my server and it says

cannot set headers after they are sent

to the client

so we can have only one response per

request

and in order to avoid that we just go

with return so always always when you're

setting up the condition make sure that

you go with return so that way we are

returning from our callback function and

one we set up over here and that way

you'll avoid those errors now of course

in this case there's no more code to

read so

yeah it is a better practice if you just

put this return here but you won't get

the error since again there's nothing

after that and one more thing that i

would like to mention

normally you're not going to set up a

separate one just for the query yeah

there might be some cases maybe there's

some apis who do that but normally again

you can just add it to where you're

getting a list

so basically if

there's a query beautiful you're maybe

gonna sort that data you're gonna filter

it you're gonna i don't know set up some

pages or whatever and if

no query string parameters are there

then you send back the whole product and

if you take a look

pretty much nothing stops me here from

just changing this to api and products

and the functionality is going to work

where if

there are some query string parameters

present beautiful

notice how we're filtering

our product if not then i always send

back these products anyway and as you

can see those are just copies of the

products that are coming from my data js

hopefully that is clear and now let's

move on to our next topic

nice and once we're familiar with route

params and query string let's really

kick things into gear and talk about

middleware in express.js

express middleware are functions that

execute during the request to the server

each middleware function has access to

request and response objects

and when it comes to functionality

literally sky is the limit in order to

hammer this home i have prepared quite a

few examples where we cover middleware

step by step since in my opinion actual

code examples are far more helpful than

text based explanations before we

continue though let me just stress

something middleware is literally

everywhere in express

you can even make an argument that

express apps are nothing but a bunch of

middleware functions stuffed together to

make one nice express cake or dessert if

you are in that sort of thing

and since that is the case middleware is

not one of those topics you can just

skip or avoid

it is at the heart and soul of express

so please don't dismiss it with that

said since you'll encounter it more than

once if you struggle with it in the

beginning don't panic the more examples

you'll do the better you will understand

it now let me start by cleaning out my

app.js and this is going to be the case

where i will leave

the code at least some of the code from

the previous lecture so let me delete

all the middle part and i'm just going

to leave express we are instantiating

our app and we're listening on port 5000

and let's just start by adding a comment

here

for your reference so there is a

incoming request

and so far we have been just sending

responses right

so what middleware does

it sits in between

hence the name so middle where over here

and then we pass the response so the

request comes in we'll do something so

we'll have access to the both to the

request and response we'll do some kind

of functionality again the most basic

you can just cancel log something

and then we'll send out the response and

again i know it probably looks confusing

at the moment but trust me the more

examples you'll do the better you'll

understand

and let's start by simple scenario where

i have two routes i have the home route

and i have the about route

and in those routes i would just want to

log

the method that the user is using the

url that the user is trying to access

and for example a date

and if you think that's silly there's

actually npm packages that do that

because

as your express apps grow bigger and

bigger it is very useful to see those

incoming requests in that manner so

let's start here by setting up add.get

again this is going to be my home page

and for time being i have my callback

function i pass it in and i just go with

the res dot send

and i send back the home and i'll do the

same thing here with my about

so there's going to be two routes at the

moment home and about unless it's just

going to say about so i'll save it and

it's not going to be surprised if i

navigate to localhost 5000 if i refresh

this is my home

and this is my about again something we

have covered already before now here's

the kicker

if i go with logger

and if i set up that functionality in

the route forward homepage i'll also

have to do that in the about so let me

showcase that so i have request object

and in there i have method i have url

and i'll simply set up the year because

i don't want to deal with javascript

types so let's go with method now that

one was on request

dot method property then we also have

the url so url here and that is going to

be a request url property

like so and then like i said i'm going

to go with const and i'll name this time

but in order to make it easier i'm

actually going to get a full year so i'm

going to go with new date and i'll

invoke it and i'll say get full year and

invoke it as well

and of course i'm sending back home yeah

that is nice but before i do anything i

would also want to

cancel console.log all three of them so

method url

as well as the time like so so i save it

and now every time

user is gonna hit this resource of

course i'll see that in a console log so

there it is if i go back to my home page

like so and if i refresh quite a few

times

there it is now in a console i can see

that the method was get so the user was

trying to get the resource and then the

path was the homepage that's my url and

then the year is 2021. okay awesome

but here's the problem if i want to have

the same functionality

in about what do i need to do right now

well again i need to copy and paste

now if i have 15 routes does that sound

like a reasonable approach of course the

answer is no

a better solution would be if we set up

a function

and in that function we have all this

logic and then i can just attach it

really nearly to all my routes and when

i say well in italy it just just means

that for some routes i maybe want to

attach it and for some maybe i don't

so here's the deal i can go above both

of my routes and i can just simply say

that there's going to be a function by

the name of

and for time being we're not going to

look for any parameters but yes there

will be there

and then we just take

all our i believe four lines of code

right and we just cut it out and pass it

here okay awesome and now of course

where do we attach this function so we

don't have to duplicate our code

and the place is following where we have

the path and then we have the callback

function now in between them we can

stuck a middleware so in this case as

you can see i'm referencing the function

please keep that in mind so i'm going to

go with logger that's my middleware

function

but now there's the second question well

in the logger i'm accessing request

object right so

how can i do that

because at the moment i'm not passing it

in well the good news is that express

passes it in to our middleware function

so in here i just set up the reference

for my function and express will do that

behind the scenes it will supply the rec

res and also a next and you'll see in a

second why we need this next function as

well so again

we don't have to do anything we just

pass here the middleware express

supplies them but of course it's our job

to access them as parameters and then

set up our logic so for them being i'm

not going to do anything with next i

will save

and we should see something where in the

console i'm still going to get my log

but the problem is going to be in the

browser so if i navigate back and if i

refresh

notice something where i have this

spinner

okay

so what's happening here well i

successfully logged

but i didn't pass it on to the next

middleware so here's the deal when you

work with middleware you must must must

must must pass it on to a next

middleware unless you're terminating the

whole cycle by sending back the response

and don't worry there's going to be

examples where we do that as well so for

now just keep in mind that when you have

a middleware

where you set up some kind of logic

unless you're sending back to response

yourself for example since i have access

to response i simply can go with res dot

and send and again i'm going to come up

with testing or whatever it doesn't

really matter what we send back if we

refresh notice it doesn't really matter

if i try to access the home page since i

have my middleware i'm actually sending

back the testing and this is why the

middleware is so so

powerful because you can literally do

whatever you want over here you can set

up all kinds of cool logic

and you have two options either you pass

it on to the

next middleware which in our case of

course

are going to be our methods our get

methods or

you simply terminate the whole cycle and

you just say res dot send and i'm

sending back my own data so let's not be

brutal over here i will actually remove

this line of code

and if

i want to pass it on to the next

function meaning in our case that is

going to be my method app.get i simply

go with next and we have to invoke it

again please keep that in mind there's

going to be more functionality later in

these middleware functions but you

always always

either you terminate

so either you send back your own

response or you pass it on to the next

middleware that is very crucial so now

if i go again to my homepage

there it is i successfully navigate to

my homepage i can clearly see that that

is my response and i also successfully

logged in my console

the method the url as well as the full

year and now of course instead of adding

this logic line by line to every request

simply can go and i say yep i would like

to invoke the logger here as well so if

we go to logo host 5000 and if we're

brave enough and we navigate to about

there it is now i have get request about

url as well as the full year hopefully

that gives you a good initial

understanding how the middle works

and now i can talk about more

complicated topics beautiful we are

familiar with the middleware we have our

first middleware function

but there are two issues with this

current setup first

our appdress is getting somewhat clunky

because

i mean we have this logger then we have

the methods

it's definitely nicer if we have this

logger function in a separate file

it's just going to keep our app.js lean

and in turn it's just going to make it

easier for us to navigate and

essentially work with our application

and the second issue what if i have 50

more routes

and i don't want to add this function

manually to all of them

wouldn't be nicer if there would be a

method that essentially just adds my

middleware function to any route and of

course the answer is yes there is such a

function in fact we used it a few videos

ago now let's start though by moving

this sucker into a separate file

so i'm gonna go to my not navbar app

sorry

this is what happens when you have a

bunch of

projects open meaning a bunch of folders

open let me go here where i have my

app.js

and i'm just going to

create a new file

and this is still going to create it in

the final sorry so let me go here and

i'll create a new file and i'll call

this logger

js now if you really want you can add

the middleware there in name as well but

in my case i'm just going to add

the name of my function

then i'll cut it out

and what's really cool that we know how

to export this right so we have cons

logger and then we go with module

exports and we'll just set it equal to

our logger so now we have default export

that's our logger so of course in the

app js i simply need to go with const

logger is equal

and then i require it i go with logger

and if i navigate to localhost 5000

i still should see in a console my log

and if you do then everything is correct

so that's the first part

now the second how can i apply this

logger

to all my routes

so for example

let me just copy and paste these ones

and i'll say api

and then

product

and then api

and i don't know not about maybe items

again doesn't really matter what you

place here i'm gonna go with products

as well as items

again i can add them manually but the

more routes i'm going to have

well the bigger issue this is going to

become right

because for every route i need to

manually add this logger so a better

solution is this one

where i select all of them i just remove

them like so now of course if i go to

any of these routes i'm not going to

have anything in a console but

there is a method by the name of app

dot use and in that app.use

this is what we do we pass in the

middleware so we simply go with logger

and once i save

check it out now if i go to about for

example or if i go to home

or api

and then products and hopefully you get

an idea

all the time you'll get this log in

console why well because app.use

will invoke this for any route now

please do keep in mind two things first

order matters here

if i'm gonna place this below

app.get

and if i'm going to try to do that in a

home page i'm not going to see anything

in the console why well because i invoke

my use only after get and express

everything goes in order so if app get

is before the used one the one that

applies to all the routes then yes

well first we'll hit the home route and

then we'll send back home so there is no

logger so that's why you'll see all the

middleware functions all the app.uses at

the top of the document

so you'll have your middleware functions

first and only then you'll have all your

roth methods whether that's get post and

you get an idea so that's the first

thing that i would like to mention now

the second thing that i would like to

mention

is the fact that we can add here a path

so if i go to app.use that's my method

and instead of providing only one

argument which in my case is the logger

i can set up a first one and that is

going to be path and i just need to come

up with a value now in my case i'm going

to type api

and you'll see e in a second why so if

you save with an api you'll notice

something interesting where this is

going to be apply to both of them to the

products as well as the items so here's

the deal once you apply this path over

here basically it's gonna apply to any

route after this api so for example if i

go with api and then some crazy one home

about and then products all the time is

going to keep on applying this

middleware so that's something new right

because previously we worked only with a

specific route so forward slash or about

or products here in this case so of

course these are different now when we

add this path to use then of course it's

going to be applied pretty much to

anything that comes after the path that

you provide over here so in my case

since i provided api and of course it's

going to go for any path that's after

that now if you want to find out more

info about app.use i suggest navigating

to docs again we're looking for api

reference in our case that is four and

if you take a look at the app.use

mounts specified middleware function or

functions and we're gonna cover that

later as well at the specified path and

middleware function is executed when the

base of the request path matches so this

is going to be our base

and then whatever comes after will still

invoke that middleware function and if

you omit the path then it's just going

to be applied to all of your requests so

if i were to remove the path

now it's going to be applied to home

about api product

as well as api items nice we're familiar

with app.use

and now i want to make our example even

more interesting by adding another

middleware function and in the process

we'll take a look at how we can execute

them in that use what is the syntax in

order to add it as well as what is the

execution order

and let's start simply by creating a new

file and i'm going to call this

authorize

authorize dot js again

i'll zoom in just so you can see that is

the file name and in here i'll just set

up a function similarly to how we worked

in the logger one so i'm going to go

with const authorized

or authorized it doesn't really matter

now it's going to be a middleware

function so of course i know that i'll

have access to rec res

as well as next and then in function

body for time being i'll just invoke

next and maybe i'll cancel log i'll say

log and authorize

like so okay let's save that one

remember that we need to export it so

module

exports and that's equal to

authorized awesome and then in the

app.js i'll just copy and paste

and i'll say

authorize like so

and of course the file name is also

different it's not a logger so we can go

with authorize

and once i have this setup in place

the way we execute

multiple middleware functions in app.use

we simply place them in the array so i'm

gonna go with my logger first so logger

and then we're gonna go with authorize

and now once you navigate to a localhost

5000 again any of them in this case

because notice there is no path

first in a console i'll see this get and

then authorize and that's something to

keep in mind where they will be executed

in the order so if we flip this one

if i go with authorized first

and then i go with logger then of course

in the console i'll have the opposite

order where i'm going to have authorized

first and only then get so that's

something to keep in mind now i'm going

to go back to my previous setup the

logger and then authorized and now let's

take a look at how we can have the if

condition in our middleware function now

before we do anything let me just stress

something very very important where this

is just for demonstration purposes this

is just an example and it's not how

we're going to authorize

users in our express applications i just

don't want to overwhelm you from the get

go so i'm just going to show you simple

example using the query string but again

this is not this is not how we

authorized users in our express

applications and with that said i'm

going to navigate back to my

authorized middleware and in here

i'm just going to set up a query string

so i'm going to say if the user

provides a query string

in my url then i'm good to go then i'll

send back the resource that the user is

requesting however if the user doesn't

provide the user query so query string

parameter in the url then i'll just send

back 401 which just stands for

unauthorized so let's start i'm going to

go with const and i'm going to be

looking for specific query string i'm

going to be looking for the user my url

parameter and of course we know that it

is available in rec dot query like so

and i'm going to say if the user exists

so if it's there with any value it

doesn't really matter which one or i

don't know maybe if you want to make it

more interesting let's go if the user

equals john okay if that is the case

then i'm going to go with rec.user

and notice what i'm doing here

i'm actually adding a property of user

onto the rack object

and i'll show you why it's so powerful

so i'm going to go with recuser that one

is equal to

whatever i mean that could be a object

for example and i'll say here name john

again this is just for demonstration

purposes and then id i don't know four

or three or whatever so that's my user

now i still need to call next if i won't

do that then the whole setup is gonna go

bananas so i'm gonna go with next here

and now of course i just need to set up

a response if

the

user or whoever is visiting

doesn't provide the query string with a

key of user and then value on john and

in that case i'm going to go with my

else and i'll say

res

and then let's add a status and the 401

is going to be for unauthorized and

let's just say send and simply let's

try to spell this sucker

unauthorized let's save that one

and now notice something interesting

if i'm going to go for example to my

home page or product again any of the

routes because there is no path

in my app.used check it out i have

unauthorized and if i inspect and in the

network tab the same deal i have 401

because i'm not authorized to access

this resource i have my authorized

middleware whereas say you didn't

provide the query stream parameter with

a key

of user and more specifically you didn't

provide here a value of john

and since you didn't do that you cannot

access the resource so now of course if

we change things around and if i go

with my question mark and if i say user

equals john

what do you know i have my home why well

because now the condition is met and now

we just go to next now why it is so

powerful because in the authorized we

add the user right so now of course not

only i can check for that query string

parameter but and also access this info

again

this is just demonstration normally what

you're going to do you'll check for the

json web token and then if the token

exists then we communicate with database

and actually get the user again this is

coming up for time being we're simply

hard coding these values so back in the

app.js in any of the routes now i'm not

going to add in all of them but just to

showcase

i'm gonna add for example in app items

i'm gonna set up here a log and i'll

look for

rec and user and you'll notice something

really cool where if i leave this

query string parameter and if i go to

api

and items

check it out first of all i have the

items and second in console what do i

see over here i see that user and that's

why it's so powerful because we can add

our middleware

we can do some kind of functionality and

now basically i'm attaching this to my

request object so i have the request

object and now i'm attaching this

property here and now in any of my

routes now of course i went with items

but in any of my routes i'll have access

to that user that's why middleware is so

so crucial and that's why it is a big

part of express applications because it

truly allows us to structure our

applications as lego blocks so we have

this piece of functionality we have that

piece of functionality and when we

combine them we have this nice working

express server now like i already

previously mentioned

middleware is all over express

so just because we're done with our

initial introduction doesn't mean that

you're not going to see middleware

you'll see it all over the place but

just to complete our initial

introduction i want to cover two common

questions first well if we have access

right now to app.use since we know how

to use it

are we going to add the middleware in a

route and actually the answer is yes

because imagine the scenario where

i don't want to apply this app.use to

all my routes

for example i only want to check for

authorized users in the api forward

slash items what do i do well i simply

add my authorized middleware correct so

now i'll be able to access all these

routes without any issues but the items

want yes

i'll check for that silly query string

parameter and if you're wondering well

how we can pass two middlewares if you

would want in a single route

same we just simply grab this array so

we copy and paste and now of course once

i hit the items not only i will log

but i'll also authorize

so let's go back

and i'm going to take a look where in

this case everything is fine

i was able to access the resource since

i provided the john so notice here name

john id number three i also have my

console log but if i were to go

to just my home page like so i have the

home and as you can see i don't get

anything in a console i don't get my

logger

and i'm also not looking for any kind of

authorized user so that's the first

thing that i would like to cover second

what are our options when it comes to

middleware so far we have covered the

first one our own so we can always set

up our own middleware now our other two

options are express so express provides

quite a few

built in middleware functions again in

this case we don't have to worry about

setting up the functionality we just

need to reference the docs to see what

options are provided and then of course

supply those values and if you remember

the express app example

we used app.use and i said put the pin

on this i'll explain this a little bit

later if you want you can retype this

but in my case i'm just going to copy

this from the for express app.js

and if we copy and paste and if i place

it here notice so this is a app.use

method now what argument the app.user is

expecting it is expecting a middleware

so in express

we have a built in middleware by the

name of static again somewhere in the

express source code there is a code

similar to this now of course this is

silly they have way more complicated

setup but hopefully you get the gist so

there is a method and the only thing

this method is looking for our public

folder and then i already told you that

it basically places all the contents of

public folder

as our static assets so they're publicly

available so we already covered that one

and now let me show you a simple example

of third-party middleware now for a

third-party malware we'll have to

install it and one of the most popular

ones i guess for the login is this

morgan npm so again just go to your

search engine and type morgan npm that

is going to direct you to the

docs i guess for the morgan and as you

can see in order to install we just run

npm i morgan so that's how we install

the package and the syntax is following

where we just go with morgan we required

a morgan and then we just pass in morgan

tiny now of course

this one we need to set it up in our

app.use so this is really optional

you don't have to install it you don't

have to run it but in order for me to

hammer this home i will do that so let's

go back i'll stop my server and remember

the command was npm

i and morgan okay i installed this one

so now of course this package

is going to be in my dependencies like

so so not only i have expressed i also

have the morgan

and then in the app.js of course i'm

going to have to require it so i'm going

to go with const morgan and that is

equal to

require and then again i don't have to

provide the path

that's the module that i installed so i

go with morgan and then where i have

app.use

and go with app.use since i would want

to add to all my rows again if you want

to add for specific one there's a

different scenario but if you want to

add for all the routes you just go with

morgan

and then they basically give you

multiple options and the tiny one is

just going to provide you the most

essential data and again if you want to

reference the docs please do so so i'm

going to go with morgan and now i just

need to spin up my app and i go with npm

start now i will remove logger and

authorized from my api items

just because i think the terminal is

getting quite busy

and now of course once i navigate for

example home page

in a console i have get i have forward

slash now this is a status code and then

i have 2.8 milliseconds and that

essentially just signals how long it

took for the server to respond and if i

were to go to localhost and forward

slash about now of course i'll see that

i have get request i have about the 200

and now of course time is a bit

different as well so hopefully this

gives you a general idea

why middleware functions are so crucial

and how powerful they are and yes the

bigger your express applications will

get

most likely the more middleware

functions you'll have

now

they could be your own ones they could

be the ones that provided by the express

or

there's also going to be tons of

third-party middleware functions

not bad not bad we have general

understanding how middleware works in

express and now i want to cover

rest of the http methods

so

if you remember which seems like an

eternity ago we covered the cycle the

request message as well as response and

in request

well

get was by default performed by browser

but of course we have other methods as

well and i also provided a second slide

just for these methods and here you can

see rest of the methods so get is again

by default set up in a browser and this

allows us to read data then we have post

that is for inserting data so for

example if we have some kind of api

orders route we can add an order so user

makes an order and we just place that

order on the server so of course

eventually we would say that in a

database then we have put if we want to

update data and of course we also have

one for deleting the data and before we

continue let me just mention something

we're not going to persist this data so

yes we'll have working examples of post

put and delete and hopefully i'll be

able to convey my message

in a manner where you understand the

general setup for rest of the methods

but since we haven't covered how to

connect to database we won't persist

this data now i could have went the file

system route

where essentially we are persisting this

data by writing in a file but i thought

it's a waste of your time because most

likely you're going to work with

database anyway so we might as well skip

that part so once we understand how we

can connect to the database what are the

methods by working with data in our

database then we'll have a proper

example where we're persisting in

as well

and in order to kick things off i'm

going to navigate back to my address

again the previous example is going to

be in the file number 10 middleware

options

and again we're just removing pretty

much everything starting with morgan so

right after app

and all the way to

app.listen

like so

now there's not going to be a home route

however i'm going to go with api and

people now why do i go with api people

because in the data file in the data js

where we had the product

there's also this one people people is

an array each person is an object

there's an id as well as the name as you

can see very simple example

so

with this data array i want to showcase

how we can read this data how we can add

for example an extra person

using the post how we can modify the

person

as well as deleting one and now of

course i want to navigate to app.js and

first i want to get my people so we

simply go

with import i'll structure it right away

and as a side note since i might make

some modifications i'll use let in this

case

and i'll set it equal to require

and then data hopefully this part is

clear since we have covered it quite a

few times and let's start with the one

that we already know and that is going

to be a get method so i'm going to go

with app dot get like i said i'll

purposely set up my route with a value

of api and people so that's going to be

my path i'll say api

and then people now this is a get method

and simply will return

this array so rec and res and again i'm

just going to go with res status let's

hard code the value of 200 then let's

set up our json and since i want to be

kind to my users i'll send back the

object i'll say that the success

property is true so the request was

successful and as far as data property

well i'll set it equal to people so

let's navigate back to our browser and

we're going to go with 5000 and of

course cannot get

so this is going to be 404 if i just go

to the homepage

and instead

i have a route for api

and i believe the whole path was people

like so so we run that

and now of course i have zoomed in

already massively here so let me zoom

out

in my browser and we should see

that we're getting our object the

success property is true beautiful and

then of course we have the data property

and in there we have the people's array

so a bunch of people in here so of

course that is our first http

method

that is the get one where effectively we

read the data and like i already have

mentioned

probably 20 000 times

that's the default

method that the browser performs so

when you set up a request with your

browser you right away use the http verb

by the name of get and that's why you

can read the data

all right so we're clear with get method

that's how we can read there however how

we can add data onto the server so how

we can

insert data

and in order to do that we need to use a

post method

but it's not like i can somehow

configure browser and start making post

requests unfortunately that's not how it

works that's why i provided a little bit

of help now keep in mind one thing where

after we set up a post method

effectively once we take a look at two

flavors of how we can set up post

request we will install one more tool

which is going to be crucial

in our express server development which

is just going to allow us to

test everything much faster

but since for the post i do want to show

you two flavors that we can have

we'll use a little bit of static data

meaning there's an app that i prepared

but don't worry

it's not like you'll have to do that

each and every time to test any of these

methods and you'll see what i'm talking

about in the following videos so first

let's start by jogging our memory a bit

we have app.use now what

app.use is doing is just applies the

middleware

to all our routes correct and i also

mentioned that we have this option

of setting up a public folder

now we can call whatever we would want

but for this methods example i prepared

a

methods.public

as you can see it is just a folder with

index.html with javascript html

some css

and once we navigate there of course

i'll show you how the functionality

works so this is just prepared so we can

test those other methods meaning more

specifically the post method because we

cannot simply just perform a post

request from the browser so first let's

set up

that methods public as our public folder

that's step number one so let's set it

up as our static assets and in order to

do that i'm just going to add first a

comment and i'll say assets and then i'm

going to go with app.use again remember

that is our method and this is going to

be a built in middleware

and the name is express static so i just

grab my express instance i look for the

method of static and if you remember we

just need to provide here a path

and instead of going public or static

like i showed you previously i'm just

going to go with forward slash and then

methods and then public

because this is where i set up my static

files for these examples we invoke it

and now if we go to the home page we

shouldn't get this error so once you

invoke

there it is we have a

somewhat decent looking html file with

two options we have this javascript

option which we're going to cover second

and first one is going to be a

traditional form example and again the

reason why we do that

is because you cannot simply just

configure

your browser

to perform

a post request you either need to use a

tool which we're going to install by the

name of postman or

insomnia here's another popular one

or you need to set up basically a

working application

and if you take a look in the methods

public we have this working application

all right and once we have the basic

setup in place now let's take a look at

our two flavors when it comes to the

post method

and i want you to navigate to index html

and in there you'll find pretty typical

index.html file with some styling

with nav as well as deform

and in form we have two attributes we

have action one

as well as the method and as you can

clearly see the value for the method is

post

and this action one just says

where we're going to send it and notice

now we have forward slash login so that

means that

this url this path is on our server but

of course we know that in the app.js

we're not handling that

so for the form there's going to be one

path and then for the second example

when we used straight up javascript then

of course there's going to be a

different path for that so this is going

to be the url or path where we're

submitting the form and inside of the

form we have label we have input

so basically

we have name attribute for this one we

have the id

as well as the autocomplete so we'll

type in some kind of value and then

we'll send this to

forward slash login so localhost and

then forward slash login and of course

we also have a submit button so now

let's start by taking a look what

happens when we simply submit this form

so go here type some kind of gibberish

in my case i'm going to go with john

bravely press enter and of course we do

have kind of post login okay that's fine

we're not expecting anything anyway

right we know that there is no route

that handles the post

for the login

but what's really interesting here

is in the network tab of course i can

see

my request

in this case this is login now this is

404 and again i'm going to repeat this

20 000 times but check out the method so

method is not

get method is post and then we're going

to localhost 5000 and then forward slash

login now what's also really interesting

all the way in the bottom

what do you see here you see this

forum data

and then we have key value pair we have

name and john and if you remember

when we talked about http messages i

said that the body is optional so for

example when we're sending a get request

we're not sending a body

but when we're sending a post request

it's very crucial so if i want to add

something onto the server

of course i want to get that data

i mean otherwise how i'm going to know

where to add to the server doesn't that

make sense i hope it does so let's go

back okay i see this name and i see john

and if you're not familiar basically the

way it works is whatever you provide

here

for the name is going to be a key

so for example if i'm going to set this

up as

testing you'll see that now when we

perform the same request the same post

request again with the same value

different value it doesn't really matter

now of course that key

name is going to be testing so whatever

value you provide over here that is

going to be the key and of course the

value is whatever you're submitting so

in my case

it's either peter or john okay

that's out of the way so i'm going to

change it back to name and now we need

to understand something

where the request is coming in

but a we're not handling that

and b we don't have the middleware that

actually adds this data that the form in

this case is sending to our request so

let's see how we can fix the first one

and we simply need to come up with a

round now in this case remember we're

dealing with post this is not get

and we're going to go with forward slash

and then log in here because of course

that's what i have in my form again we

go with rec and res

and technically we can come up with some

kind of info i can say send

and

i'm simply going to say post

and that's it just so we can save time

on typing again let's navigate back and

in this case let's try susan let's send

it yeah i see the post so i don't have

the 400 anymore or 404 so that's cool

but unfortunately i have no access at

this point to whatever

i'm being sent

so unfortunately i cannot access that

susan or john or whatever value so

unfortunately

i cannot add for example to my list if i

wanted to now how do we add it well this

is where the middleware comes in so

previously we covered static assets with

express static

in order to get the form data

we need to go with url and coded

middleware so i'll add here

parse

form data and essentially this is just

going to parse that data and add the

values to

rec.body so where we have a post request

in the rec.body property we'll find all

the info

and in order to use this middleware

surprise surprise we're going to use

app.use

and then we'll pass in express

and then url encoded and then you also

pass in flag where you go with extended

and you set up false and if you're

wondering why are we adding this

extended false flag or you just want to

get more info about this url in coded

middleware simply let's head back to the

documentation in this case we're looking

for the express and notice here i have

express url encoded this is a built-in

middleware function in express it parses

incoming requests with url and coded

payloads and it is based on the body

parser so in the previous versions of

express you have to actually install the

body parser now in this case you don't

it already comes built in and as far as

this extended this option allows to

choose between parsing url encoded data

with query string library when false

meaning

this is our case or the qs library when

true again i wouldn't lose my sleep over

this one then the common approach is

using this extended and false and once

we can access it then we can do some

cool functionality so first let's just

scroll down a bit where we have the

login and first i'm just going to start

by console logging rec

and body let's save that one

and again back to our browser

again i'm going to go with susan this

was 200 so everything was successful and

now of course in the right dot body i

also have a name and the value is susan

so

now we can start doing something with

this data now i purposely set up two

examples

one is going to be for form which of

course is this one and then one is for

javascript now with the javascript

example this is where we'll actually

manipulate this people array fourth time

being with login this is a separate

issue we're just dealing with the form

so

we'll just try to make things

interesting by checking for the name

if the name is provided then we'll send

back welcome and then pass in that name

if the name is not provided so for

example if the user

is trying to submit the form empty for

example like so we'll just send back 401

please provide credentials again

please keep in mind this is just a

example and i'm fully aware that we can

check for empty values here on the front

end again the goal of this example is to

show you how to handle this on the

server so i have wrecked that body okay

i can see that in this case i have

name but it is empty so now of course

let's set up our logic first i'm going

to go with const name and that one is

equal to rec

that body so i'm destructuring my name

property and i'll just check if the name

exists whatever the value that could be

b

that could be bobby lee not could be

again taco burrito whatever you want and

as you can see i'm getting quite hungry

so let's go with return res

dot status

then let's set up a 200

which just says that we were successful

and we're gonna go with send

and we'll set up a template string

welcome and i'm just going to access my

name

so if there's some value i'll send back

200 and i'll say welcome whatever is the

value if not

well here we're going to go with res

and let's just add status here and again

just for kicks i'm going to go with 401

and we're going to go with send and of

course let's say please

provide

and credentials

like so

let's save this one and now we should

truly see how it works in the action

now i'll leave i guess the tab for now

and let's just try to submit so for

example if i submit with empty values

i'm going to say please provide

credentials and as far as my login it is

401

that's what the server is sending back

however if i type in some kind of value

for example anna comes to mind i have

welcome and anna so that's our first

flavor when it comes to post request

where we use the form and again this is

just front end where we come up with an

action and since this index.html is on

the same server we simply go with

forward slash and login of course if

your front-end application is separate

from your server then you're going to

provide a full path where the server is

hosted so basically a full domain and

then we go with method post now this is

technically a front-end part but it is

crucial that we understand it so then we

perform of course a post request we hit

our url

so in this case we hit our forward slash

login and this is the part where we

handle that on a server

in order to get that data

whatever we are being sent we need to

use a middleware this one is built into

express so again we simply just need to

use

app.use which is going to apply this

middleware to all our incoming requests

and then we just pass an extended false

flag and the moment we do that

indirect.body

will have access to our form values so

whatever

is set up here as a value that is going

to be our key and whatever is passed

into our form well of course that is

going to be the actual value that we're

getting so if i go here with name i'm

gonna see either susan anna or whatever

user provides now like i already

previously mentioned this is just for

demonstration this is just so we have a

bit more interesting example e instead

of just sending back the name

so hopefully this part is clear

and now we can focus on our second

flavor where we use javascript to

send the request all right and once we

have the form set up out of the way now

let's take a look at the javascript

option before we do though there's one

more thing that i would like to mention

if you take a look at the headers

you'll notice something interesting

where we have a content type for the

request header and of course this is

going to be application

and then we have this form url encoded

and the reason why i'm showing that

because of course for javascript it is

going to be a bit different so just keep

this one for your reference now

let's navigate back to our

static files basically to our front end

and now let's take a look at the

javascript approach

and interestingly here

where i have the javascript i do have

the form

keep in mind we'll still handle this

form but in this case it's going to be

done strictly using javascript and we'll

use javascript to send our http requests

and that is very very crucial that is

going to be the difference where instead

of form now i'll be sending that request

using javascript

and of course the content type will be

different that's why i showed you the

form example but what you'll also notice

that right away we have our list and if

you don't believe me you can double

check in data we have john peter susan

anna and emma so what's happening well

let's go to javascript html

this is where we have our frontend logic

and again let's take a look at our index

html

a little bit of css

nav

and then we have the form now in this

case i don't have the action and i don't

have the method

okay interesting so i have name

attribute it still has a value of name

so i should expect probably that this is

going to be the value that's coming in

with my request then i have a little bit

of form alert this is where we'll

display a little bit of functionality as

well as the result

now if you're not familiar

there's a package called axios which

essentially just makes it easier to set

up http requests

so

instead of using the built-in fetch

which i could have used i think axios

provides a cleaner api and better error

messages

and since i don't want to spend three

hours on explaining all this code

i simply went with axios and the way i

set it up i just set up the cdn link so

this just gets me the axios library and

then the moment i install it of course i

have axios in my front-end project

please keep that in mind those are two

separate things this is a front-end

project and

in order not to confuse you more i just

set up a few script tags instead of

going with a separate javascript font so

as you can see here i'm selecting the

result

so that is my div

and i have this fetch people

so that is the function that fetches

people from my server now notice the

path

it is api and people

why well because

in my server i have also api people so

this is for get requests

that's the default one however in this

case we're not doing that with a browser

we're doing with javascript so axios

has the method by the name of surprise

surprise get that just means that on the

front end we're performing a

get request

to the same server that's why we go

forward slash api and then people so

make sure these urls match

so if these paths won't match then

you'll have an error and to showcase

that if i go with p poles

then if you navigate to the front end

and if you refresh

can't fetch data

so we try to fetch people from our

server then we do a little bit of logic

and this is just vanilla.js not going to

cover it basically we tear it over and

then we just set up a nice heading 5s

and all that and then we invoke the

function but

if there is an error we'll look for the

error property now in this case i'm not

the structuring it i'm actually not

using it i just say can't fetch data so

that's step number one now the second

one is of course using the form

so then i select the submit button i

select the form i also select the alert

because we will display an alert if the

value is empty and again let me repeat

i'm fully aware that we can check for

that in the front end i just wanted to

showcase the server setup and then

notice something interesting where i

have this try and catch block in my

functionality so the moment the user is

submitting the form of course i invoke

my callback function it is a sync

because

for the actuators i can wait for

response and notice this one so i have

axios and again surprise surprise the

method name is post why because we are

sending a post request

and this is just an axiorys thing but

again we provide the value in this case

the url value is api and people so

something that we're not handling yet on

our server and this is the value

so again this is just axio syntax where

in order to set up whatever data you're

sending you just pass it as a second

argument and you set it up as a key

value pair now what's really cool that

would axios they set up all the content

types and all that good stuff for you so

again you just save a little bit of time

now if there is an error in our case

that is going to be if we're trying to

submit something and in fact there's no

value meaning we just try to submit

empty form value then we will display

the error message and again this is

really cool because axiorys just

provides

a very useful

error api unlike the fetch where you

really need to

jump through the hoops so let me save it

back to people so we can see of course

all the people

that

we have in our array currently and then

of course we'll focus on this post one

so as you can see i get the input value

and i just passed it in as a

name property awesome so now back in our

app js of course we need to handle it

and please keep in mind one thing where

app dot post

and then api

and people

is not the same as api get and api

people

even though the url is the same

methods are different and that goes for

all the methods we're going to use

whether you're talking about put delete

or whatever so just because the urls are

the same

doesn't mean that they mean the same

thing no

the method is different here i'm just

reading the data i'm reading data from

api people here i'm actually trying to

add data

and again we're going to go with wreck

and res

and let's just go with some simple

response

now for time being i'm just going to say

that my response is going to be 201 now

that's the response that we send back if

we are performing a post request and we

are successful so i'll just say res that

status 201

and for time being let's just say send

and i'm just gonna say success and of

course now what i would want

is to navigate back to my javascript one

hour fresh i'm getting all my people and

now let's try it out so i'm gonna send

this one

so i sent again here nothing changed but

if i take a look at my network tab

i should see and by the way sorry i'll

have to do that one more time let's go

with i don't know susan here let's try

to submit and there it is now of course

i have api people and 201

so that's the response that i'm getting

on my front end so let's bravely click

on this one and we can see that the

request url is api people okay

the method was post now the response was

201 so it was successfully created and

now check it out when we look at the

request headers of course we have

application json so on our front end we

do need to add this content type

when we are sending the data now again

what's really cool about axios it adds

for us

but in general you need to keep that in

mind and there it is again we have this

request payload

and the name is equal to susan so

whatever i'm going to pass it in if i'm

going to send it empty then i'm going to

still have the key name

and the value will be empty now the

gotcha here is even though we're

handling a

form submissions we're not handling the

json data so yes we know how we can send

back the json data but we're not

handling the incoming json data and this

is where another middleware comes into

play so i'm going to say parse json here

and we simply need to go again with

app.use

and we go with express

and json now in this case i'm not going

to go to documentation

if you want you can do that in my case i

will try to save us a little bit of time

and we'll skip that and here we have api

people and now similarly to our login

we have access to the form data that is

being sent with javascript in the rec

dot body

previously

before this was added no we have no

access yes when it comes to form that

was one setup now when it comes to

straight up http requests for example in

this case sent with javascript no we had

no access so we were getting a json

and now we added a specific middleware

that handles that so of course in this

case now we can set up more logic

correct we can say that we're looking

for the name and if the name is provided

then awesome then i'm going to send back

that new person that was created so we

can add it to our front end and again

this is the case where we're not

persisting this data anywhere later

we'll learn how to do that for now i

already have the code that adds it to

our front end however if the user tries

to submit without any values well then

there's going to be a error message so

in the api people

in the post method let's set up our

logic

where i'm going to go with const name is

equal to

rec.body

the middleware makes it possible now

and then i'm going to say if the name is

not provided well then i'm going to send

back the 400 then i'm going to say

please provide name value so there's

going to be a error message so i'll say

here if and

exclamation point and if the name is not

provided then let's go to return

res

dot status and for the request error we

go with 400 that's the status code and

then let's go again with json and in

this case we're gonna go with success

now this success will be false and then

we're going to go with message again i

would suggest using the same properties

because of course i'm handling them on

the front end as well so in here i'll

say please provide

name value like so now if the value is

provided whatever it is then of course

we can send back res.status 201. hey

guys it's john from the future with a

small update

as you'll see in a second while i was

recording i forgot to change the methods

so instead of writing json i just left

it as send

and while we can get away with it in

this example normally you always want to

use json instead so make sure you change

your method from send to json and in

this case

let's just set up a proper object we'll

say success is true so now we're being

successful and i'm just gonna send back

that person now i'm going to set it up

with person key and the value will be

named whatever i'm getting again please

use the same ones if you want to have a

same result now

let's navigate back we can refresh just

so we are all on the same page and if we

type susan now we should see another

susan added to our list

and then again we can go with john and

i'm just being lazy on coming up with

original names and as you can see every

time we add

value in our form we're being successful

we're actually getting back this value

from our server and then we dynamically

added to our front end and again the

reason why we're doing this way is

because we're not persisting this data

so that's why the setup is following

later of course we'll learn how to

persist this in a database as well and

if i try to submit with empty value

check it out now of course i have people

and this one is what 400 right

notice here and it says please provide

name value now if you want to do a bit

of console logging you're welcome to do

that on the front end if for example you

are iffy about the syntax but just to

let you know when we talk about axios

here

effectively we're getting back the whole

thing so when we perform a request http

request with axiorys we're actually

getting back a

giant object

now what we're interested in that object

is a data property

so that's the response that is coming

back

from the server

and then in here as you can see i set up

a heading 5 with data.person so that's

the person that we're sending back from

our server now

if for example there is an error we go

with error response again data property

because that's where the useful

information sits because the object of

course is giant with lots of useful

information but as far as what we're

sending back it is sending in data and

then message now i'm looking for the

message property of course here because

i set up a message property

on the server hopefully it is clear this

is our second flavor

where effectively we perform a post

request from the application

and of course in that case we do need to

provide content type as well as the data

and next video we'll install

and cover some basic setup for a very

useful tool

that is going to save us a lot of

trouble when we work with post

delete as well as put methods

all right so at this point we're

familiar with two ways how we can send a

post request

so we covered how we can do that using

the form

as well as straight up http request in

our case using javascript

however there's a major problem in our

current setup

and the problem here is following

if

we need to create a frontend to test

something for every route as you can see

i mean our development is going to be

extremely slow

because we can clearly see that it's

probably going to take us way longer

just to set up a front end than setting

up just one simple route so every time i

create a route i'm probably going to

spend i don't know five six times more

on setting up the front end where i can

test this route and of course there has

to be a better option and that better

option

is a tool called postman

and postman is just awesome for quickly

testing our apis so at this point i

strongly suggest that you navigate to

postman.com again it's a free tool so

you're not going to have to pay anything

but for mainer of the course yes we'll

use this so if you're kind of iffy about

installing something new this is

something that is required so navigate

to

postman.com

and then they'll try to sign you up you

don't have to do that just keep

scrolling down keep scrolling down and

all the way in the bottom you'll see

this download app option go here and

they'll right away detect which

operating system you're using of course

in my case that is mac so download the

application once it's on my computer i'm

going to navigate back to the desktop

i'm going to go to downloads i'll crack

it open

then of course i'll just move it to my

applications like so and i already had

one on my computer but i removed it so

we can do these steps together then this

is the application let me zoom in that's

the postman so just click on it

and then it's going to spin up the app

and eventually

you'll hit the dashboard and i'm not

going to spend half an hour on this

setup but of course as we're progressing

we the course as we're progressing with

our examples we will cover

more features

that this app provides

and basically here you'll have all your

requests that you can actually group in

collections and again that's something

that we'll cover a bit later and this is

where we can make those requests and in

order to create a new request we just

click on this plus sign and check it out

so at the moment i have untitled a

request

in here i need to enter the url and i

can send my request not orders here on

left hand side what do i have i have get

but what's really cool i have all these

methods available as well so first let's

test out the get route and then we'll

see how we can deal with post route as

well now as far as our url what it is

well it is localhost 5000

and of course the full url is api and

people now this is for the post as well

as the get and since we're testing it of

course that's why we have a method with

the value of get so let's go here local

host and then five thousand

then forward slash api

and people and the moment i click send

check it out what do i see here in the

bottom i see my object the success value

is true and there i have my data so as

you can see the moment i create my route

for example post route or put route or

whatever i can test it immediately i can

test it within a few seconds instead of

building the whole front end just so i

can test one route and of course once we

have covered get route now let's see how

we can deal with a post route so we need

to change the method of course

now the url still stays the same because

i do have a route for the post as you

can see and in here what i'm looking for

i'm looking for the name

in the body

and how do we construct a post request

in a postman well we do that in a

following way first we go to the body

and we look for raw

and instead of text i go with json

because i'm going to be sending a json

data so this is not the case where we're

working with the forms in this case

we're sending a json data and what

you'll notice something really

interesting in headers right away

there's going to be a content type

so let's see let's set up first the body

and you'll see how it gets added so

we're gonna go here with a name again

this is what i'm looking for that's why

i need to pass it and then i'm gonna set

up some kind of value now since i'm

setting up the json please remember that

we need to use double quotation marks so

i'm going to go here with john and if

you paid attention previously we had

eight headers and now we have nine so

i'm gonna go back and there it is now i

have content type application json so

that's really cool we don't have to do

anything the header gets added for us

and of course the moment i click send

check it out now i have success true and

person john why do i have that well

because that is my response i have

success true and of course whatever name

i received i just sent it back so now of

course let's quickly test out our 400 as

well so i'm going to navigate back and

then in the body i'm just going to send

a empty string or you can remove name

altogether that's really up to you and

now of course i have 400 bad requests

and success is false and of course i can

see the message so as you can see we can

test it within seconds and to really

hammer this home why don't we create

another post route and quickly set up

some kind of response and let's test it

out in our postman as well so i'm going

to go in between the post and login i'm

just going to go with app.post

and the route is going to be following

i'm going to go with path of api

people

people

and i'm going to add a postman here

or you know what let's do it this way

let's go postman

and then

people like so

and then as far as the callback function

again

we get rec res

and then

in the body again i'm going to be

looking for the name property so i want

to get that name so i'm going to say

that i'm expecting it

we'll go with name rec

dot body again if you want to cancel log

the body you can do so but i think we

have done that quite a few times so i'm

going to omit that then i'll copy and

paste

my response so again if the name is not

provided meaning if the property is not

there or if it's just empty i'm sending

back to 400 however if i'm successful

then i'm just going to take my array

i'll add that extra person and i'll send

it back now i'm not going to add the id

i'll leave that one blank because

eventually database will do that for us

so i don't really see the point of doing

that manually so i'm going to go back to

my api postman people and then again

this is my error response and now let's

copy and paste our status and then

instead of sending that one person we

created why don't we do this why don't

we go with data

and then of course the array name is

people and now as you can see i'm using

the spread operator and i'm just going

to add that one single person so i'll

save now of course we do need to change

the route so it's not going to be api

it's going to be postman

and then people like so now let's add

for example peter and the moment i click

send there it is i have my success true

and as far as data

all the way somewhere should be peter as

well so again we just grabbed that peter

and then we added to our array hopefully

this makes sense and now of course we

can work on other http methods as well

all right and once we're familiar with

postman now let's work on the other two

methods

so now we're gonna be working on put

method as well as the delete

so i'm gonna scroll down and below the

post login route i'm gonna go with app

and then put now again this method

is for editing the data so put method is

for update

and again the convention is following

where if we have a list for example in

this case that would be api and orders

if we want to edit

or delete we go with our route parameter

where effectively we set up a route for

api orders and then we go with colon id

and this is going to get me that one

specific item now please keep in mind

one thing where this is a convention so

technically there are multiple other

ways how you can set it up but there's a

reason why that convention exists and

that's why throughout the course we'll

stick with this convention i'll cover

the official name of this convention a

little bit later as well as a bit more

details about it for now i just quickly

want to cover both of the methods so i'm

going to navigate back i have my put

method that is for modifying the data

and in our case what is the url for the

whole list because that is api people so

this was just for testing correct and

then we go with api forward slash

and then we go with people

and then of course i also want to add

that id so this is going to get me that

one specific item and again the reason

why we're doing that because when we'll

send our

put

or delete requests we'll send to a

specific path

so this is going to be that one item and

if that item exists

then in the body there's going to be

data to update

or in the case of delete there's going

to be nothing in the body we'll just

remove that item and you'll see how it

works in a second so please be patient

so we're going to go with people and

then remember again we have route params

and in this case i'm not going to call

this person id i'm just going to say id

just remember that we can call it

technically whatever we would want and

now in this case there's two things that

i'm looking for first i want to get the

value here in the params and remember we

access that using the rec params and the

second thing when it comes to update

when it comes to the put request

i'm also going to send something in the

body why well because if i'm updating

for example if i'm changing the name

from peter to susan or whatever of

course i also need to supply this value

so you need to understand that there's

two sides of this request

not only we're looking for that specific

item that's why we use the params that's

why i specifically say hey i would like

to get the item number one or item

number two i also need to supply this

value because otherwise what's the point

of updating something so let's access

both of those things let's say that i'm

gonna get the id from rec params so this

is going to tell me which item and then

the second thing since of course i want

to update that item i need that value as

well correct so we're going to go here

with const

and i'm going to be again looking for

the name and we'll say reg dot body

and that's it that should do it so these

are the two values that we're gonna get

from our question and just to make

things interesting i will console log

them right now so i'm gonna go back to

the postman and remember we need to

change the url it's not gonna be api

postman in this case it is going to be

people and now you can select any of the

ids whether that's one all the way up to

the five so we go here with one

and then as far as the value what is the

value for the first one it is john so

kind of makes sense if i'm updating that

i go with peter correct so we have put

request we have api and then people and

then check it out the moment we send it

now of course the request is hanging

don't worry about that but in a console

we should get api people and then the id

and of course the reason why i don't see

anything because i was smart enough and

i didn't console log anything so i'm

gonna go back with id name and you know

what for timing let me just send back

hello world okay let's go here

let's actually send it one more time as

you can see could not get the response

that was the error this time in this

case i am getting hello world so that

worked beautifully and as you can see

the status code is 200 as well and then

in the console i have one

and i have the repeater so this is going

to be the id

and of course this is going to be the

value now if i'll change it of course if

i'll say number two and if i'll send it

again i get back my response and now the

value for the id is due hopefully this

makes sense so now of course at this

point we need to set up the logic again

we are going to set up the logic with

our local data with our people array

eventually in next examples we'll work

actually with database but the main idea

is exactly the same

where from the postman while we're

testing we're sending the id

in the url basically we add that url

parameter and then in the body we'll

send the value so that part won't change

just the functionality in here and as

far as this functionality well since we

have a simple javascript array first i

would just want to get the person with

that id

if the person doesn't exist

then i'll send back the error response

and if the id does exist then i'll just

change the value now i'm not going to be

looking for the error message if the

value is not provided we're going to

cover that once actually we work with

database i think is just going to be at

the moment waste of our time so let's do

it people

i'm going to remove both of these

console logs hopefully you understand

how we supply both values in the postman

and i'm going to start by

creating a person and this is going to

be equal to people

dot find again i have the array so i

have access to all the array methods and

then

if the person id matches

to my params id then of course i'm going

to get the person now let me check in

the data notice i still have it as a

number so i'll have to change the type

as well so i'll say if person id is

equal to a number and i'll pass in the

id that i'm getting from my params

whether that's one five or maybe it's

going to be id that doesn't make sense

all right good and if the person doesn't

exist well then i'll send back the

response now again in order to save us a

little bit of time i'll scroll up and

i'll look for any of my error messages

since i just want to copy and paste and

change some values around so in this

case i'm going to look for this name if

it doesn't exist

then of course we have the error and in

our case of course we just need to

change it around if the person doesn't

exist so if we cannot find that in the

array then we're sending back 404

remember that was the status code if we

cannot find the resource and as far as

the response we have success and of

course it's going to be false and now

let's go with message and in the message

we're going to use a template string

we'll say no person

with id

and then i'm just going to pass in the

id

so that's the first

response if

of course the person doesn't exist so if

in the primes we enter for example value

six

we know that we have only one to five or

abc now the second thing if the person

doesn't exist now of course i just want

to iterate over the array

and for that specific person for the

person whose id matches my params value

i'll change the name since i'm expecting

that one to be in the body again we're

not going to deal with this error for

now we'll do that once we work with

database and we're going to go with new

people

new people here and we'll say people

map so i'm iterating over my array again

i'll reference each and every person as

a person and i'll say if person id

matches to that one i have in params so

number id again

then i'm going to say person name since

that is the only other property i have

is equal to my name now where i'm

getting the name because i'm getting it

from the body

so if the id of the person matches to

that one in the params then please

change the name that i can find in the

body if not

then simply return a person return

a person and now of course all the way

in the bottom i'm going to go with res

dot

status and then we're sending back 200

since the request was successful as far

as the json we go with success or sorry

not super we're gonna go with success

true

and then as far as data well now i'm

sending back the new people so let's go

back

at this point i have two

so let me change it back to 1 because i

know for sure the

first value was john so again

the path is api

people

and then id of 1 and i just want to

change it from john

to

peter so let me double check in data

this should be john uh it's a good thing

i didn't go

with the idf2 since that one is already

peter so now let me send it and check it

out

now i have success true

and data

of course is my array and instead of

name being john

for the person number one now the name

is peter and of course if i'll do the

same thing for example

for the person number three again we

send it back of course now i have three

peters because i just keep changing

those values again we're not persisting

that data but while we're making

requests you can clearly see how we are

modifying this data and we do that using

http put method

and then of course the path

is api people and then whatever the id

and again the whole reason why is that

happening because on our server we are

handling that

all right and the last method i would

like to cover

is a delete method so below the put

method below the modify option i'm going

to go with app and the method name is

delete again the convention if you have

a list is going with a list url and then

add that specific id because the setup

is going to be extremely similar to a

put one now the only difference is going

to be that of course in this case when

we're deleting we're not expecting

anything in the body

the user hits the url for example api

people and then one we just remove that

sucker from our list that's it

so let's go down where we have

app delete and again the path is

following where we go with api

and then people

and again let me stress one more time

something where these routes are

different

when we talk about app.get and api

people when we talk about

app.post and api people or even if we

talk about app.put and app.delete

just because the path is the same since

the method is different

these are different requests that is

crucial please don't think that just

because you have a different method you

have to set up a whole new path no

you can have the same value for the path

if the method is different that is

totally different request so let's go

here again with our callback function we

should already be comfortable with this

one we have rack and res and in this

case i'm not gonna the structure out the

id from the prompts i just want to

showcase that we also have this option

of accessing the params directly so

first again i want to look for the

person then we'll send back this

response and yes oftentimes put and

delete are going to be extremely similar

and then if the person does exist then

of course i'll just filter out the array

and remove that person from the array

since again the whole point of this

request is to remove that person from

the array so in this case

you can actually copy and paste and i

know that some of you might find that

annoying but at the same time we do need

to speed this up and start working with

a database so hopefully you can forgive

me i'm just gonna grab everything

starting with the person all the way

until the end of our error response d404

let's scroll down copy and paste and

this is what we're trying to do so i'm

trying to find a person whose id

matches that in the params and of course

in this case i haven't destructured out

the id right so i just need to change

this around where i go with rack

and then params and the id again the

setup is exactly the same the difference

is that i'm directly accessing the

params object and if the person doesn't

exist

then we send back d404 so let's try this

response

i'm gonna go back to my postman again

the api is people but we need to change

the method right so now i would want to

delete and since i want to test out the

error and as a sign up you can send the

body doesn't really matter we're not

handling that on server anyway so it's

really irrelevant but since i want to

test out the error i'm going to go with

abc so again the path is localhost api

people and then abc and if everything is

correct i should see the error and of

course there is but something tells me

that this is a different error so let's

go back and check it out and of course

the issue is following notice here in

the json how i'm accessing the id now of

course i haven't destructured it right

in this case i went with rec params and

then the id so i'm going to go with rack

params and the id let's save it and

let's try one more time again i'm

looking for a person whose id doesn't

exist so i'm gonna get the error and

there it is i have success

false

and as far as the message no person with

id of abc so i was looking for the

person

with id

that's not in my array so that's why of

course i got back the error response so

now i'm gonna go back to our app delete

request and here i just want to filter

out the array and the way we're going to

do that i'm going to go with const new

people

is equal to

people.filter

that's my array and i'm just filtering

it i'll pass in my callback function

and

i'll reference each

object with the person parameter

and i'll just say if person

id

does not match

the id found in rec dot params then

return that person

if it does match then it's not going to

be included that's why we go with

exclamation point and remember that we

still get our id as a string so we must

do the number one first and then only we

go with params and the id so that's our

new array without that specific person

whose id

matched the one in params so now of

course let's just go with our return

return

res

dot status

here and this is going to be 200 of

course

and i'm going to go with json and we'll

set up our object success is true

and i'll send back the new people array

so we're going to go with data and then

new people let's save it

and let me test that out e in the

postman where of course now i'm gonna go

with id

that is in the array and that's gonna be

number one so if i send notice how it is

irrelevant if i send body

again because i'm not handling that on

the server anyway but

if i take a look at my data

well the person with id number one

john is missing why well because his id

matched to the one that i passed in the

primes so now of course he was removed

from the array so if i'll go with five

same deal now the john is back here

because again we're not persisting data

but

the person with id of five has been

removed from the array hopefully this

gives you a good understanding how we

use other methods as well not just get

and why we go with postman instead of

setting up the front-end but before we

cover

router in express let me just stress

something

that yes

while we're developing our server of

course we'll use postman because you can

clearly see how much faster it is i set

up the route and i quickly tested

otherwise if i would have to build a

front end for every route that i'm

creating i mean the process would be

just very very long but at the end of

the day

when you set up the api

the expectation is that there is going

to be someone who's using that data now

that could be on your own server so for

example if you're building a full stack

application with mern that's one of the

options that could be decoupled

application remember how i showed you

a example where i have the api on my

server but then there is a react

application that uses it it doesn't mean

that you have to build that front-end

application yourself

just be mindful that the whole idea of

setting up the api

is that someone is going to be using

that data that's it that's all i want to

say and now of course we can talk about

router in express

all right i think we're moving along

quite nicely

but as you can see the moment we're

starting to have

more routes

and more functionality

we have another issue and that issue of

course is the fact that our app.js

is getting quite busy and technically we

don't even have that many routes so what

is the solution well the solution is

using express router where we can group

those routes together

and then as far as the functionality and

actually set them up as separate

controllers

now eventually

in the next example when we work with

database i'll cover again the common

setup

which is called mvc basically it is a

pattern it's not a rule but it is a

nicely used pattern when you're setting

up the api but we are missing the model

part in the mvc pattern because we

haven't connected the database so i'll

just leave it at that just please keep

in mind whatever i'm about to show you

in this video and in the next yes it is

a pretty common convention and pattern

so

i also suggest sticking to that now also

i want to mention that in this video

we will do a bit of copy and pasting

meaning we'll have to refactor the code

because i think this is a perfect

example for us to set up the router

where we already have some code so you

can clearly see the benefits of setting

up the router instead of me coming up

with some empty routes and then saying

that yes that is the best pattern so

with that said first where we have the

request the post request for api postman

people i want you to change this around

a little bit so as you can see i keep

going back and forth in this case i want

to go with api people and then let's

just say postman again it doesn't really

matter we're not going to make requests

anymore from the postman in these

examples anyway this is just about our

code structure and then once we change

this around i also want to move this

login up just so it's a bit clearer what

we're doing so take this login route and

keep moving moving moving moving and

just place it on top of your routes

and there it is now of course i have my

login and now notice the pattern

whereas i have one route for the login

but then rest of them i have api people

api people api people postman

api people id

and hopefully you get the gist again i

have api people id

so wouldn't it be nicer

if i could somehow group all the api

people and also add one for the login

but basically in a separate file and the

way we can do that is by setting up the

router now again common convention

is just creating another folder

so i just want to make sure that i'm

actually doing that in the express

tutorial let's create a new folder

and common convention is calling this

route and then you just come up with

whatever name you want now in my case

i'm gonna go

off for the login because

we're just gonna imagine that maybe

there's going to be one for register one

for logout or whatever

and then there's going to be one

40 people so that's going to be for my

api and people so let's set up these two

files i will zoom in massively just so

you don't think that i'm cheating so

let's go here with alt js this is where

i'll place my login one and also right

away set up my

people

people

just okay awesome i'll start working in

people.js because it's going to be a bit

interesting and then we'll do the same

thing in the auth as well

and the way we set this up we simply

start by requiring the express so we go

here express require and of course the

module name is express and then instead

of setting up the app we go with router

and we explicitly get the router from

the express so this is going to be a

router instance

that takes care of the routing instead

of the app

so

we're not going to do the routing

anymore in our app.js well sort of we

will we'll use the middleware but as far

as the specific urls we'll handle that

in this routes people file and the way

we set up the router we go with router

and that one is equal to like i said

express dot and then we go with capital

letter router and then we invoke it

awesome

that's a great start we can save this

sucker and now i want you to go back to

app.js

and don't grab the login that's why i

set it up separately above all the

routes but grab all of the ones with api

and people so take these suckers here

all the way

up to delete

basically stop at listen cut it out

and then copy and paste in people like

so okay

great so now of course i have all my

routes here

now our next step is actually changing

from app

to router because i want the router to

handle the routing so in my case i'm

going to select all of my apps like so

so i'm just doing that with command d

in the visual studio code and

at this point i should have multiple

cursors like so and i'll set up my

router

and now all the way in the bottom

i want to go with module

not exports and of course at the moment

i'm exporting my router

and then once we export a router of

course in the app.js

i want to set up a app.use where i'll

say yes for the path that starts with

api and people

i want to use my people router and the

way it's going to look like we're going

to go back

and

at this point we have people here and as

a side note actually we need to cut it

out but we're not going to use it here

as well eventually the setup is going to

be different so for now yes

please cut it out and copy and paste in

people but since we'll be setting up the

controls we'll have to do that one more

time anyway so i guess i'm going to go

below the router i'm going to look for

my people otherwise my functionality

won't make sense and in this case

remember

we are sitting already in routes so i

need to go two levels up and i still

need to look for my data correct so now

of course our functionality should work

hopefully we don't have some weird bugs

and then like i said in the app jess now

of course i would want to use my

app.use so i'm going to go below express

json and i'm going to say app.use and

now i need to set up that base route now

what is my base route here well it is

api and people correct

because

this is just my route and then in some

cases i have the postman or i have the

id

that's it but the base stays the same

okay awesome so we provide this path we

say api and then people and now i want

to set up that router

and of course in order to set up the

router

i need to import it

and you can call it people router you

can just call it people again

that is really up to you i'm just going

to say people is equal and now we need

to require it and remember we have a

folder by the name of what routes

and then we also have people file okay

awesome we require our router

here correct

so that's our router and we're exporting

awesome so we get the people and like i

said with use we can use the path if we

want so this is not going to be applied

to all of them this is only going to be

applied to the ones

that start with api people and then we

pass in the people we'll save it but

there is a problem you see once we set

up this router

with a base path

in the people

actually we have a mess right now

because we already have the base

for our router in app js where we have

api people and now in the people.js if

you check it out we actually have api

people forward slash api people so i

fully understand that this is going to

look a bit drastic

but in order for this to work we

actually remove everything we remove

that base so we go here with just a

forward slash why well because we

already have the base here we have api

people

so that's how the route is going to

start

and then

we just have the forward slash so this

will match whatever i have in the

address

and since in the get and in a post both

of them just have api people well i

simply go with forward slash again i

fully understand that this might look a

bit confusing in the beginning but again

the more routers you'll set up the

easier it's going to get so this will

just match

whatever path i have here whatever base

path i set up in my app.js so i'm just

saying yes i'm using this people router

and in the people since i already have

base path in place i can simply

reference it using the forward slash so

this is going to match whatever i have

in app

and once i have spent what seems like an

eternity on the base path i can keep on

scrolling and again notice i have api

people and then postman so what's the

only thing that i need here it's just a

postman because i already have api

people so i remove this sucker here

keep on scrolling

then the same with id right we only care

about this one that's the whole point of

setting up the router so we can start

splitting up our functionality in

multiple files same goes with this last

id

and even though i think i said that

we're not going to use the postman i do

want to quickly check

and i'm going to go with get simple if

the get works trust me the other ones

work as well so we go here with api

people we send but unfortunately i get

the error hmm that's interesting so let

me check i think the problem here is in

the app.js

i don't have the forward slash so let me

try this one

let me send it one more time and there

it is now of course everything works so

my apologies i forgot to add here

forward slash that's why we were getting

the error and of course everything works

i can go with get i can get my list

if i want i can also maybe delete a

person so i'm going to go delete and

we're gonna test three so let's see we

send and as you can see

the person with id of three is missing

so as you can see our route works so

that's the first step so now here's the

challenge

try to repeat the same thing with login

now with login

it is going to be a bit simpler because

we don't have that long of a path but

again stop the video and try to set up

the login yourself and then once you're

ready resume it and we're going to do it

together

how was it hopefully you were successful

and i'm going to give it a shot so first

remember we needed a file so in this

case i do have auth js awesome

so i'm just gonna cut this sucker out

from my app.js

and place it in off then of course i do

need to have the boilerplate for the

router so again let's go with express

require

we require the module by the name of

express of course then we set up our

router

router and that one is equal to express

dot router we invoke it then we change

this value

around like so

and then we're just gonna go with module

and then export and that one is equal to

our router we do this

then we navigate back to app.js and

we'll have to import it as well so we go

with auth i guess let's call it that

and we're looking for auth file

that's where our router is coming in and

then of course i just need to set up my

middleware myapp.use where i provide a

path of what well of login and in this

case i'm going to be more careful and i

will add the forward slash and of course

i'll set it up as auth so let's save

this one and then the only thing we need

to do in the login

is simply change it around where i'm

already handling the login in the app.js

so forward slash login so again my route

now is forward slash login so i simply

go with the forward slash i already

covered the route in the objects so

i don't need to do that anymore in here

and you know for this sucker just to

make things a bit more interesting

why don't we use the browser now keep in

mind you can still use the postman if

you want but i'm gonna go the browser

out so we're gonna go with new window

i'm gonna go with 5

000 here

and of course this is going to be the

small screen i have traditional form so

let's go with some kind of name peter

and i send and i have welcome peter and

of course if that is the case i know

that my functionality works so we are in

good shape again probably the most

confusing thing

is this one where we use app.use to set

up our route so all the routes

that will start with this api people are

going to be located in the people.js in

the routes folder and in there instead

of using app we use the router and then

since we already have the base

setup in the app.js

when we have a route that exactly

matches the base we just go with forward

slash now if there is something else

after the base route so some additional

info of course then we go with forward

slash which just means that we match the

base path and then we add whatever value

we want

and hopefully you can see how much

cleaner is our app.js

where now we're splitting up the

functionality in separate files

for our routes beautiful i think we

really clean up our app js

but we're not out of the woods yet

if we take a look at our auth js yeah

this one looks somewhat clean but we

need to keep in mind that we only have

one request

we only have one post request to our

login however if we take a look at our

people.js

it is still somewhat of a mess because

we have a bunch of functionality since

of course we have more routes

and of course a better setup is if we

would be able to split this up into a

separate file and i'm talking about the

functions so imagine this scenario where

we only would have a router

then i'm gonna set up my method whether

that's get post or whatever then i'm

still gonna have the route but the

functionality this one the controller

is going to be in a separate file so

it's going to be a separate function and

you'll see how much cleaner our file is

going to look like just in a second so

again we need to head back to our

express tutorial

now i'll zoom in

i'll create a new folder

and again common convention is calling

this controllers

for the reason that there is a pattern

called mvc so model view controller and

then again we come up with the name in

my case i'm going to go with jobs or i'm

sorry not jobs i'm going to go with

people and i'm not gonna set up one for

the other one for the auth since there's

only one but for people i will set up a

controllers file by the name of

people.js and here

i just to set up first my functions

and the way it's going to work we're

going to go with const and then again

you just need to come up with a name so

for example for get request where i'm

getting people i'm just going to call

this get people keep in mind this is

just a function so the name is really up

to you and since i'm going to have the

same functionality of course i need to

keep in mind that i do need to have

access to rack and res now it's really

cool that once i pass this function as a

reference it's still going to work so i

simply go here with this rack res and

set up the functionality now probably

faster is just going to be doing like

this where i cut out

and then back into controllers i copy

and paste now i know that some people

might find this annoying but yes i'm

purposely refactoring the code so you

can see the benefits right away and i'm

going to do that for all the functions

and

for a little bit it's gonna probably

look messy

where i'm gonna do the same thing for

the post so i guess first i'm just gonna

cut it out and then back in the

controllers nothing routes in the

controllers let's come up with that

function as well so const and in this

case i'm going to call this create

person

i'll copy and paste the code

okay awesome

back in the routes let's get the postman

one so in a controller let's also call

this const and create

person

and postman like so copy and paste

that's my function then back in routes i

have one for put

so i think it would make sense if i call

this for example update person again cut

out everything

starting with a function and then all

the way to the closing parenthesis

cut it out

back in controllers we're going to call

it const

update person

like so copy and paste and lastly let's

deal with a delete one as well

so let's keep scrolling

again we cut everything out

like so

and then back in the controller let's

create one for deleting the person so

const

cons delete person

and copy and paste and if you remember

which seems like an eternity go

when we covered the exports i said that

of course we can also use right away

module exports and then whatever so for

example in this case that could be get

people or create person or

create person postman now in my case i

always prefer to do my exports all the

way on the bottom where i say

module exports now this is going to be

the object and now i just want to access

all the functions keep in mind

it doesn't change the functionality

functionality is the same where i'm

basically exporting an object

with bunch of functions so here i just

need to reference their names so it's

get people it is create person

create person postman

then update person and lastly it is also

for deleting the person now one thing

that is missing of course is the people

like i said this is just going to be

temporary

so i'm going to go to the controller

here

and i'll copy and paste now in this case

the path is correct because

the route was already in a separate

folder so

that

should still work and of course now i

can save my controllers and in the

routes what i need to do is of course

import all of them

so in this case we go with const and

again i'll write away the structure all

of them so let me just copy and paste i

think it's going to be faster

like so since the names of course are

going to be exactly the same i

destructure them and i'd structure them

from

require and then of course we're looking

for controllers and then more

specifically i'm looking for the people

like so and once we have required them

of course now we pass in the function

reference so for example here i can say

get people now i do need to add a comma

and if everything is correct our

functionality is still going to work

so in the controllers we're still

accessing rack and arrays

and we're still sending back the

response but of course the benefit of

all of this work

is the fact that our routes file is

gonna get much cleaner so in here

remember the name was create person

like so

and then we have one for create person

postman

and let's set it up like so then we have

also one for update

person and lastly we have one for the

leading person right so we go here with

delete person i save again i'm not gonna

test all of them out but i'm gonna go

with for example delete

and i'm gonna look for four this still

works

i remove the person number four

and also if i check out the get one

for the people this also should get me

back the array so i know that my

functionality still works but i nicely

cleaned out my file now lastly before we

talk about the databases i just want to

mention that when it comes to setting up

the routes

we actually have two flavors so i'm

gonna comment these ones out and i'll

show you another way how we can set up

the routes and effectively the benefit

is that we can set it up in fewer lines

of code keep in mind the functionality

is going to be exactly the same so again

this is going to be the case where it

comes down to your preference if you

prefer setting up your routes this way

you can definitely do so there's no rule

against it if you prefer the method that

i'm about to show you then of course you

can use that one instead so we go with a

router and then we go with route and

then in the route i set up the path

and again since there's get and post

that match exactly what i have in base

same situation i just set up the forward

slash and instead of setting up them

separately for example get and post i

can just chain them so chain one after

another so i go with get that is of

course my method

that is not changing and then i need to

pass in my controller function okay as

you can see

almost the same in this case however i

can change it now the method names did

not change the paths did not change

they're still

actually referencing the base path in

here what we have in app.js but since we

can chain it we can simply write it in

one line of code so of course the

callback function is gonna be create and

i believe it was person so create and

person like so

then we have of course one for the

postman so in this case of course it's

not going to change it's pretty much

going to be the same logic where we go

the router route

like so and then we go with forward

slash postman and then of course i want

to chain

dot and i believe it was post right and

then we go with create person postman

and then we can again set up one line of

code for the put and delete so in this

case i think i'm going to just copy

where i have router dot route then we

set up our route and in this case it is

going to be forward slash and then id

and then we have two we have one for put

and we have one for delete so we go with

delete and then as far as the callback

functions we go with update person

and also we have delete person and

finally let me just stress it one more

time where whichever setup you choose is

really up to your preference

functionality is exactly the same we go

with router route and then we can just

chain our methods and add the callback

functions

now in this case we set up each route

separately so for example if you have

multiple urls that match yeah you're in

good shape you can just set up router

route pass in the url and then chain all

the methods and lastly let me just

quickly test it one more time since i

made some changes i send it and there it

is i successfully get back my people so

with this in place

with our router in place

with the fact that we have covered all

the methods

the get post put and delete i think

we're ready for the next level where we

connect our server

Can't find what you're looking for?
Get subtitles in any language from opensubtitles.com, and translate them here.