Node.js Flashcards
What does Mosh hope we become after this course?
(Hint: Superstar Node developer)
A superstar node developer
Why?
Most comprehensive, most up to date node course
Shows all modern ways to build applications in node
What is node?
an opensource, cross platform
runtime environment for running Javascript code outside browser
Used to build services that power client apps (Web app, Mobile App)
What is node ideal for building?
Highly scaleable, data intensive, real time backed services that power applications
What is so special about node?
(Hint: How is it different from ASP.net, Ruby on Rails, Django)
(faster developement)
Great for prototyping and agile development
(better performance)
Build superfast and highly scaleable backends
Ex. Used by Paypal, Netflix, Uber
(more developers)
anyone with Javascript skills can work as a full stack developer
(cleaner, more consistent source code)
same tools, conventions and best practice (Javascript full stack)
(largest open source ecosystem)
free open source libraries to use
What big tech companies use Node?
(Hint: Uber, Paypal, Netflix, Ebay, NASA)
“We have seen with our proof of concept a tremendous amount of improvement on the response times: for our current APIs we have a steady response of 2 seconds and the Node.js API that we hosted was responding within less than 100 milliseconds. That’s a very promising statistic for us.”
Netflix
node.js app reduced startup time, allowed more movie streaming
Paypal
node.js app outperformed java app on page load times
mobile software stack build solely in Node.js
Yahoo
Node.js has become one of their top technologies
Uber
Node.js into full production allowing quick iterations and zero risks for matching drivers with riders
Groupon
50% reduce in page loading times
GoDaddy
10x less servers thanks to Node.js
Ebay
faster iterations, 175 million users
Walmart
allows fixing bugs much faster
NASA
creating microservices architecture with separate APIs, moving data on astronaut space suits allowing faster queries
What did Paypal find when they rebuild their Java application in node.js?
(Hint: faster, less code, fewer files, faster response time)
An excellent choice for building highly scaleable applications
Where was Javascript run time environment originally?
(Hint: JS engine in browsers)
JS engine converts Javascript code into machine code
Each browser has it’s own JS engine
Ex.
Chrome - v8 engine
Firefox - SpiderMonkey
Internet Explorer - Chakra
Therefore,
sometimes Javascript code behaves differently in different browsers
Why did Ryan Daal embed Chrome’s V8 engine into a C++ program?
V8 engine is fastest Javascript engine
allows us to execute Javascript outside browser
Node.js will convert Javascript code into machine code
gives us additional objects (file system, network, server requests)
What is node.js NOT?
(Hint: Language, Framework)
Not a programming language (C#, Python, Java)
Not a Framework (ASP.NET, Django)
It’s a runtime environment for executing Javascript code!
Provides v8 engine to translate Javascript to machine code
Offers additional objects for working with servers, networks, etc.
What feature of node.js allows it to build highly scaleable, super fast applications?
(Hint: asychronous framework)
Asynchronous
non blocking nature of node.js
ideal for intensive Input/Output apps
ideal for apps that require heavy disk or network access
Why?
Node is continuously monitoring event cue for finished tasks
While event queue is empty, serves additional clients
can serve more clients with less hardware
What should node.js NOT be used for?
(Hint: CPU intensive applications)
Do not use node.js for CPU-intensive apps
video encoding or image manipulation service
Why?
Node is single threaded, while CPU runs, clients must wait
lots of work required by CPU, low requests to file system or network
What should node.js be used for?
ONLY USE for data intensive, real time applications
DO NOT USE for CPU intensive apps
Why?
Single thread get’s caught up with CPU calculations
What core modules in node.js are explored?
(Hint: OS, fs, events, http)
also learn how to create our own modules
What is the global scope object in browsers?
Window
all variables, objects and functions declared globally are accessible in this object
What is the global object in node?
(Hint: global)
variables and functions defined are not automatically added to global scope
in browsers, it is!
Why?
Scoped to their file, because of Node.js module system
Why is it a problem if variables and functions are added to the global scope?
(Hint: maintainable and reliable applications)
Javascript code often split into multiple files
if function is added to global scope
when we define function in another file
definition will override this defintion
Soln?
to build maintainable and reliable applications
create modularity
avoid adding functions and variables to the global object
How can we build maintainable and reliable applications in node?
(Hint: Modules)
Using modularity
modules or files provide abstraction and private members
create small building blocks (modules) where we define variables and functions (encapsulated in module)
variables and functions are scoped to that module (private)
not accessible outside the module unless we export them
Every file in node is a module
Why?
So that variables and functions don’t override eachother
If we want to use a variable or function outside a module, what must we do?
(Hint: export and make public)
Modules provide abstraction
making variables and functions private (not accessible globally)
to use a member defined in a module, must export it
What does every node application have?
(Hint: one module or file)
At least one module or file
Ex. app.js
How do we create and load a module?
Like classes in Java
module.exports
require( )
As a best practice, store module object in a constant
Why?
So we don’t accidentally override it
What is JSHint?
(Hint: Tool for catching compile time errors)
Can scan Javascript for compile time errors
When do we export an object vs. a function in a module?
(Hint: can export object or single function)
Exporting an object is useful if we have multiple functions or properties
(export an object)
module.exports.member = member
(export a single function)
module.exports = member
How does node create a module?
Doesn’t execute code directly
Wraps it inside a function (module wrapper function)
What are some of the useful modules built into node?
Streams
OS - work wit operating system
HTTP - create web servers
file system - work with files
process - get info on current process
query string - usefull for http services
What is the path module?
(Hint: Paths are used in URLs to specify file locations)
Built in node module
better than working with strings
useful methods for working with paths
What is the OS module?
Built in node module
gives us information about current operating system (OS)
os.freemem() - gives free memory
os.totalmem() - gives total memory
os.uptime() - up time of computer
os.userinfo() - current user information
What is the file system module?
(Hint: working with file systems)
Node built in module
always prefer to use asynch methods
What is an event?
(Hint: core functionality in node)
A signal that something has happened in our application
node’s core functionality is built around handling events
(EventEmitter)
Ex.
HTTP listening to port, client request incoming, raises event
application reads request, returns right response
What is an event argument?
(Hint: additional tasks when handling request)
adding additional arguments when raising an event
can pass data about event that just occured
listener can recieve data (event arg) and call url, log, etc.
event arg best practice - encapsulate in obj
How do we work with EventEmitter in the real world?
(Hint: encapsulate in a class)
Not directly
create a class with all capabilities of EventEmitter
use this class in application
What is the HTTP module used for?
(Hint: creating networking applications)
One of the powerful building blocks of node
ex. create webserver that listens for HTTP request
can create backend for React or Mobile
However…
In real world, we don’t use HTTP module
Why?
As we add more routes, code get’s complex, added linearly in callback function
Use express instead (built on top of HTTP module)
What is node package manager (NPM)?
(Hint: largest software registry in the world)
A command line tool and free open-source registery
for third party libraries (re-usable code)
any functionality for an app, most likely
a free open-source library (package) on NPM registery
1 million packages
11 million developers rely on re-usable, open source tooling
Share?
Can create and add to NPM
How do we install a package using npm?
(Hint: > npm i package)
How does node resolve modules?
(Hint: require( ‘./module’) )
- First, checks to see if the module is in the node core
- Next, checks to see if the module is in a folder/file in the project
- Finally, checks to see if the module is in the node_modules folder
How do we load / use a third party module?
(Hint: underscore.js module)
How do we install a third party module?
(Hint: npm mongoose)
Package.JSON updates dependencies
What should we exclude from our source control repository?
(Hint: node_modules)
exclude node_modules
Why?
It could be hundreds of megabytes in size (large)
everytime someone checks out code, have to download
Soln?
package.json stores all node module dependencies
can use npm to instal dependencies locally!
How can we exclude node_modules from git?
(Hint: don’t commit node_modules to source repo)
Create a .gitignore file
What is semantic versioning (SemVer)?
Hint: Major.Minor.Patch
Ex. mongoose 4.13.6
major version
add new feature that could break existing apps dependent on old version
minor version
adding new features, API not broken, increase minor
patch release
bug fixed, increase patch version
What does the ^ character mean?
(Hint: Semantic versioning)
It tells node…
download the current module_package as long as the major version is the same (no breaking changes will occur)
if newer minor or patch version is available, will download
Ex. Built application using mongoose ^4.13.16
six months later, someone checks out code from repository
downloads dependencies…
newer mongoose version available 4.14.0
(as long as same major version)
new minor and patch will be downloaded/installed
What does the ~ character mean?
(Hint: same major, same minor, updated patch)
Tells node to download the dependent module with…
same major version
same minor version
updated (newest) patch version
What should we do if we want someone to get exact version of a dependent module?
(Hint: remove ~ or ^)
Sometimes in real world, new patch versions break previous versions
To ensure exact module versions are downloaded…
remove ~ or ^ from dependencies in package.json
How can we see a list of all the packages (modules) installed in modules folder?
Hint: npm list
Terminal…
npm list (shows all dependencies)
To show only your app…
npm list –depth=0
How can we view information on a package (module)?
Hint: npm view package
returns package.json for module
can also go to package registry (npm registry)
check dependecies
look for current versions
How do we view only the dependencies of a package (module)?
Hint: npm view dependencies
Ex. npm view mongoose depencies
How do we downgrade or upgrade a node package?
Hint: installing a specific version
Get versions:
> npm view packagename versions
Downgrade/upgrade:
> npm i packagename@major.minor.patch
How can we view and update outdated node packages?
Hint: npm outdated
Terminal:
>npm outdated
>npm update
**only minor and patch versions updated
How to get major releases?
>download npm-check-updates
How do we update a node package to it’s current version?
Hint: use npm-check-updates command line tool
> npm-check-outdated (ncu)
> ncu - u (update)
> npm i (install)
What is the difference between application dependencies and development dependencies (DevDependencies)?
(Hint: App vs. Development)
App dependencies
required for our app to function properly
Dev Dependencies
used during development process (testing, analysis, bundling code)
**should not go in production environment where APP deployed
>npm i jshint –save-dev
package.json will segregate devDependencies and appDependencies
How do we uninstall a package (module)?
Hint: npm uninstall packageName
> npm uninstall packageName
or
> npm un (uninstall)
package.json updated and node_modules updated
How do we add a package to node package manager?
> npm login
> npm publish
Success!
Now, use in another project
> npm i package
*under dependencies in package.json
How can we update a package we have published on the npm registry?
specify version update (major, minor or patch)
npm will update version
Ex. npm version minor
v1.1.0
What are the key lessons about node package manager?
What problem does Express solve?
Hint: building lightweight, fast applications
We don’t want to hardcode if statements
What is Representational State Transfer (REST)?
Hint: Restful services (APIs)
Introduced by PhD student as his thesis
a convention for building HTTP services:
(CRUD) operations:
Create, Read, Update, Delete
*expose resources on various endpoints (customers list)
What is the client-server architecture?
client (front end)
sends HTTP requests to server (using HTTP protocol)
to save data, store data, access data
What are the standard HTTP methods?
Hint: GET, POST, PUT, DELETE
Every HTTP request has a verb that determines intention
Application exposes resource
using meaningful address
get resource, add to resource, delete from resource, update resource
GET
getting data
Ex. GET /api/customers to get list of all customers
response will be an array of customer objects
POST
creating data
POST /api/customers post new customer to collection
include customer object in body of
PUT
updating data
PUT /api/customers/1
include complete customer object in body with updated properties
server updates this customer object in customer resource
DELETE
deleting data
DELETE /api/customers/1
What is Express?
Hint: popular framework for managing HTTP routes
Express is most popular framework for managing routes
Fast, lightweight and perfectly documented
Why?
As we define more routes,
we have to add more conditional statements
A framework like Express
allows us to add additional routes while keeping our code clean and maintainable
How is using Express different than using node’s HTTP module?
We don’t have if blocks
define new routes using app.get( )
can move routes to different files
Express gives our app a skeleton (structure)
Ex.
can move all routes for courses to courses.js
What is an environment variable?
(Hint: proper way to set port in node apps)
a variable that is part of environment process runs
value is set outside of our application
Ex. Port environment variable
Process is a global object with env
Why?
In real world, port is dynamically assigned based on hosting environment
Cannot hard code it and expect port will work
What are route parameters?
essential (required) values passed with a route
Ex. Get all posts from a given year / month
Server - /api/posts/:year/:month
Client - /api/posts/2020/08
What are query string parameters?
Additional data sent to our server in HTTP request
Used to provide additional data (optional data) to backend service
Stored in a query object
Ex. /api/posts/2020/02?sortBy=name
How do we handle a GET request using Express?
How do we use POST method in Express?
app. use(express.json())
app. post
As a security best practice what should you never, ever do when working with HTTP services?
Hint: NEVER Trust what the client sends
Always validate client input
NEVER EVER trust what client sends
Soln?
NPM Joy
What is Joi?
(Hint: Client Validation)
An NPM package that simplifies validation of client POST requests
How?
provides a schema (how many chars, input allowed, etc.) for POST requests
Why?
Don’t want to validate client input at the beginning of POST request
When we send an invalid request to our server using joi, what do we get?
an error object
too complex to send to client
instead, access error message in the object
.error.details[0].message
How do we handle HTTP put requests using Express?
Look up data
If not exists, return 404
validate client req
if invalid, return 400
update data
return updated data to client
What are the advanced topics about Express covered?
Middleware
function that takes request obj
returns response to client or passes control to another middlewear function
core concept in Express
Configuration
storing configuration settings and loading for different environments
Debugging
debug package in node.js
Templating Engines
returning HTML markup to client (vs. JSON)
Pug, Mustache, EJS
Generating dynamic HTML to return to client
What is a middleware function?
An essential concept in Express
Express includes pre-built middleware
Can create custom middleware for request processing pipeline
(every request goes through request processing pipline)
Ex. logging, etc.
MIddleware function takes a request obj
AND
terminates req/response cycle by returning response to client
OR
passes to another middleware function
Ex. app.get(‘/’, (req, res) => {})
How are our middleware functions called?
In sequence
Ex. First logging, then authentication
What should we do with our custom middleware functions?
Define custom middleware in a separate module
Import (require() ) and install (app.use())
Why?
clean code practice
What are third party Middleware?
Express.js pre-built middleware
But
every third party middleware used will decrease performance (request processing time) of application!
So use wisely and sparingly
Best Practice Middleware?
Helmet - helps secure application
Morgan - log http requests
How can we enable special middleware in specific environments and not others (production, staging, development)?
NODE_ENV=Production
What is the config module?
Hint: Express third party middleware
Used for setting configuration settings - production, development, testing
can store config settings for appliction
DO NOT:
application secrets
password of database or mail server
that password/secret is available
WHY?
Check into repository, everyone can see
SOLN?
Store in env variable
How do we store our application’s secrets?
(database password, mail server password)
Hint: environment variables
export app_password=1234
custom-environment-variable.json (file)
What is the debug module in node?
Used for debugging
can set various environments for debugging
when in that environment, only debug messages from that environment shown
Ex. export DEBUG=app:*
(get all debug environment variables)
What is a templating engine?
Servers often return JSON objects
sometimes need to return HTML markup to client
Templating engines help us generate dynamic HTML / return to client
Popular:
PUG
Mustache
EJS
How should we structure our applications using Express?
Don’t write all code in index.js
First, create a folder called routes, put route logic for each API endpoint in a separate file (module) in this folder.
Import each module in index.js
Ex. courses.js and home.js which contain all the logic for the routes to courses API and home API
Second, create a folder called middleware and move logic for custom middleware to this module
How do we integrate Express with a database?
(Hint: SQL, Mongo, etc. )
Head over to Express.js and view their docs on database integration
Mosh covers mongo and mongoose later in the course in depth!
How is authentication covered in Express?
It’s NOT a part of Express
authenticating users to access API endpoints is covered in another module
What does the config package give us?
What is asynchronous code?
Asynch does not mean concurrent (multi-threaded)
single thread executes first line,
schedules next task for future
returns to execute next line of code
returns to complete task
Ex. Single waiter in a restaurant (single thread)
takes order, doesn’t wait in kitchen for cheff
only one waiter (not multithreaded)
What are the three patterns for asychronous code?
Callbacks
a function that is called when the result of an asynchronous operation is ready.
Promises
async and wait
syntactical sugar over promises
What is a callback function?
a function that is called when the result of an asynchronous operation is ready.
When the result is ready, call the result back using a function
Why?
Cannot return a value from an async function (it’s undefined until task complete)
Must use a callback to call result when it’s ready
Ex. Call the user object back when result is ready
What is callback hell aka christmas tree implementation?
Nested callback functions
Solution?
flatten structure of the code
replace anonymous function with a name function
second arg to callback is anonymous function
How can we solve callback hell?
Hint: Flatten the structure
Nested structure exists because second arg to callback is an anonymous function
Soln?
flatten structure of the code
replace anonymous function with a name function
Best?
Use promises
What is a promise?
extremely powerful when dealing with asychronous Javascript code
an object that holds the eventual result of an asynch operation
What three states can a promise object be in?
(Hint: Promise is an object that holds the eventual result of an async operation)
Pending
initially when we create a promise object it’s in pending state, then it kicks of an asych operation
Fulfilled
asynch operation is completed with a value
Rejected
if something went wrong during execution of asynchronous task, result will be an error
How do we write a promise?
Promise is an object that holds eventual result of an async operation
Initially, it’s in the pending state
if the result is completed, it moves from pending to resolved (fulfilled)
resolve - sends result to consumer
if there is an error, it moves from pending to the rejected
reject - returns an error to consumer
How do we replace callbacks with promises?
Modify callback functions to return promises
How do we consume promises?
Promises expose .then ( ) method
can chain to create complex asynch operations
How do we create already resolved or already rejected promises?
(for unit testing)
Promise.reject()
Promise.resolve()
How do we kick off multiple async operations at the same time?
Hint: not concurrency, single threaded
Single thread kicks off multiple promises at same time
not waiting for result of first asyc operation to complete
kicking off next asyc operation right away
Waiting for ALL promises to complete
returns an array
If any of our async operation fails, final promise is considered rejected
How do we kick off multiple promises and continue when the first completes?
Promise.race()
As soon as one promise in array is completed, promise at end of race is considered resolved
Promise resolves as soon as first promise resolves
Final Result is value of first fulfilled promise
What is the await approach to writing asyncronous javascript?
await the result of a promise, store it and pass it to another async function
Why?
It’s cleaner and easier to understand than callbacks and promises
Remember:
Whenever you use an await inside a function
You must decorate the function with the async keyword
What are Async and Awaits?
Syntactical sugar over Promises
Allow us to write async code that looks sync
Built over promises
JS engine converts our code into Promises
Code looks synchronous but it’s executed asynchronously
the JS engine executes this code asynchronously
await releases thread to do other work
Code still runs async
looks synchronous
errors are caught using try/catch block
What database are we going to use in this course?
Hint: MongoDb
MongoDb
noSQL database
Why?
A very popular database management system
Often used in Apps built in Node and Express
Expert?
MongoDb requires it’s own course
learn enough to get the job done here