Learn and Understand NodeJS

Learn and Understand NodeJS

memorize.aimemorize.ai (lvl 286)
Section 1

Preview this deck

call the added "greet" function

Front

Star 0%
Star 0%
Star 0%
Star 0%
Star 0%

0.0

0 reviews

5
0
4
0
3
0
2
0
1
0

Active users

0

All-time users

1

Favorites

0

Last updated

6 years ago

Date created

Mar 1, 2020

Cards (229)

Section 1

(50 cards)

call the added "greet" function

Front

available to be invoked / called thru javascript

Back

function constructor

Front

use the "new" keyword - calls the function, makes a new empty object, add properties and methods to that empty object, and returns that object automatically. - use a capital letter to help indicate that something is a constructor

Back

output from node

Front

console.log , just like for the browser

Back

The fundamental question of Node JS

Front

What does JavaScript need to manage a server?

Back

process.binding

Front

grab the C++ feature and make it available within the javascript when you use zlib you are using the JS library that wraps the C++ feature for you

Back

Object Literal

Front

Back

Web Server / Browser

Front

client / server model using the internet (http is standard Request & Response format)

Back

name / value pair

Front

can have other name value pairs

Back

v8 can run standalone...

Front

... or can be embedded into any C++ application there is an "embedder's guide" in the engine docs

Back

Object

Front

Back

you need to explicitly make code available between modules

Front

this won't just work

Back

module.exports

Front

only things attached to this will be exposed for outside use then if var greet = require('./greet') you can call greet( )

Back

./

Front

at the same folder level as where you are working

Back

invoke

Front

run or "call" the function, it's all the same

Back

a c++ file that uses (includes) v8

Front

this is a little shell -shell.cc, part of v8, - it passes whatever is given it to v8 and gives back whatever v8 gives back (may just be for windows powershell, not sure)

Back

require

Front

a function that takes the string of the path to the module you wish to import

Back

Machine Language

Front

some process converts your code into something the processor can understand - sometimes your code is converted into several different processor languages so it can be run in many places machine language speaks directly to the microprocessor

Back

util.js

Front

things you could have written yourself, but they have written for you (like isBoolean) - it's not a C++ wrapper

Back

make new greet function available to JS via V8

Front

Back

Objects sit in memory and point to other values or objects

Front

Back

An expression

Front

function expressions are possible in JS - you can make a function on the fly

Back

Argument

Front

Back

Module

Front

lots of other programming languages had this feature, but not JS (there were workarounds)

Back

JavaScript Engine

Front

Back

when I run 'print', run this print function I added

Front

Back

can access the properties of any of your obj's prototypes

Front

es6 class obj works with this,

Back

adding "print" and "load" features to v8

Front

Back

Request & Response...

Front

take standard formats

Back

Levels of Abstraction

Front

Back

shell --print_code

Front

will show you the generated machine code specific to YOUR computer's processor

Back

First-Class functions

Front

a lot of languages do NOT have this feature

Back

a function can be passed around like a variable...

Front

this is possible because functions are just special kinds of Objects no parens because you don't want to RUN the function and give it the result

Back

function expression

Front

this variable now has a function as its value it's still first class and can be passed around

Back

Server

Front

a computer performs services as requested

Back

function statement

Front

Back

CommonJS

Front

Node added the idea of modules based on commonjs

Back

pass in the whole function...

Front

javascript engine allows this kind of syntax

Back

v8 hooks

Front

if someone writes something in their JS code, it will cause MY C++ to run C++ has far more features than JS does (ex, can connect directly to a db) anything you can do in C++ can be made available to your JS

Back

v8 normally...

Front

Back

constructor example

Front

Back

C++ greet function

Front

Back

Inheritance

Front

Back

Microprocessor Languages

Front

Back

Machine Code Example

Front

what to do with what pieces of memory on your computer

Back

v8 has sets of code for each microprocessor type

Front

Back

ECMAScript

Front

the standard upon which JS is based browsers made different JS engines, and they need to conform to this core standard if you wrote your own engine, what you cause JS to do should match the spec

Back

NodeJS webserver

Front

Back

CLI

Front

Back

Client

Front

asks for services

Back

Breakpoint

Front

Back

Section 2

(50 cards)

Listener

Front

this function will be invoked when the event happen lots of listeners can be listening for one kind of event in the case of javascript, the listeners will be invoked one at a time

Back

Event

Front

we tend to conflate the 2 different kinds of events

Back

using the real emitter is the SAME as the simple, fake one

Front

... except var Emitter. require('events'); that's the native module

Back

using the event emitter

Front

require the emitter MANUALLY trigger the event with emtr.emit('greet'); all the functions in the array get called

Back

Module pattern: replace module.exports with your own object constructor

Front

a function constructor var greet3 = require('./greet3'); greet3.greet( ) if you make a change like greet3.greeting = "changed!" ... and then if you require the file again greet3b = require('./greet3') you will get "changed!" module returns CACHED module.exports even though your code calls new Greeter(), it is only ever really called once... but then you end up making only a single object but then everything references it, so all your changes persist

Back

javascript quirk - assignment breaks reference

Front

originally pointed to the same spot in memory; not anymore

Back

Custom Events - in the javascript core, this is from the event emitter

Front

often javascript code wraps the c++, so sometimes we respond to c++ events as if they were custom events core modules are built on top of this

Back

set a variable to string, use that string in bracket syntax and you can access the property on an object

Front

Back

import from json as well...

Front

Back

exports is a shorthand for module.exports , they both point to the same memory location, UNTIL you ASSIGN exports to something

Front

module.exports !== exports now

Back

an array full of functions can then all be invoked

Front

iterate over them with forEach and call them

Back

the REAL event module...

Front

has a lot more features but is very similar

Back

JSON

Front

Back

pass by reference

Front

prop1 is changed to a func and prop2 has been added when you pass in an object it will be mutated and when you are out of the function those changes will remain

Back

pass by value

Front

outputs 1

Back

index.js

Front

the entrypoint into a dir require('greet'), if it does not find a file, will look for a directory, and will look for index.js within that directory index can make multiple modules available as a single object (very common for the key and value to have the same names in this case)

Back

modules help us move towards using javascript as a web server because...

Front

Back

Mutate

Front

Back

!!! if I say Person.prototype...

Front

it's NOT the prototype of "Person", it's the prototype of any object created FROM "Person" - it establishes a prototype chain for all the obj you create!

Back

Events aren't really special... they are just prototype properties associated with an array of functions that will be called when that property is accessed

Front

the end of this file would say module.exports = Emitter; there is an events object that starts as an empty array, and then gets event names and arrays of their associated listeners

Back

you can do things to a string or number immediately - 'John'.length, 3.round.... I want a function object I can do things to, so it needs to be an expression

Front

(function( ){ }) - NOW it's a function object

Back

Revealing Module Pattern

Front

Back

when you pass an object something vERY different happens - it is passed BY REFERENCE

Front

Back

Module pattern: returning the constructor itself so you make a new object each time the file is required

Front

(gets around the problem from 71) var Greet4 = require('./greet4'); var greeter = new Greet4(); greeter.greet( );

Back

every object has...

Front

a prototype, which may have different properties than it does, but can be accessed alongside its own property (OH is this why hasOwnProperty exists? so you know what's yours vs. what's mom's?) many objects can point to the same object as its prototype

Back

restricting scope by using an IIFE

Front

first name will be 'Jane'

Back

when you assign one value to another OR pass a primitive value to a function, it is passed BY VALUE

Front

a copy of the primitive is made, and if you tweak b then a will NOT be affected

Back

the idea of modules was added by node, but...

Front

javascript engines, like v8, now support modules via es6

Back

all objects made by the constructor can access property on the prototype

Front

Back

accessing native but NOT global node modules

Front

use require: var util = require('util'); (NOTE it doesn't have ./ ... not having a path makes it look for a native module) util.log is nifty because it adds a timestamp

Back

there are several ways to set up a prototype chain

Front

function constructors, es6 class keyword (and "extends", which sets up the prototype chain) OR use an object literal let object use properties and methods of a different object makes it simple to create a sequence of objects

Back

Primitive

Front

Back

you CAN pass things into an IIFE...

Front

...it just looks kind weird

Back

to use export in place of module.exports, DON'T assign it, MUTATE it

Front

just tack things onto it :) to lower your cognitive load, you can just use module.exports, why not :)

Back

.inherts sets up an empty "proto" middleman object

Front

Back

Module pattern: return an object from exports that reveals only what you wish (this is the revealing module pattern)

Front

var greet5 = require('./greet5').greet; you cannot access or change the "greeting" variable

Back

peek the prototype of "john" : var john = new Person('John', 'Doe')

Front

john.__proto__ no need for this in real production code

Back

.__proto__ for two things from the same constructor should point to the EXACT same prototype object

Front

a reference to the SAME object

Back

since module.exports in passed by reference, it becomes the window into your code

Front

Back

global node modules

Front

you get just use them - like console.log

Back

module pattern: overwriting exports with a single function

Front

Back

Scope

Front

Back

inheriting from the event emitter.

Front

var greeter1 = new Greetr( ); greeter.on('greet', function( ) { console.log('Someone says hi'); }) greet1.greet( );

Back

Magic String

Front

event emitter, in our cases so far, is using a magic string could pull it out into a variable (remember that will work fine) - put it in a config file,

Back

.on in the real module is just an alias for addListener

Front

... and it has a change that it is a function, which makes it superior to ours

Back

.inherits in util.js takes two function constructors

Front

Back

my code is wrapped by a function...

Front

in module.js in the javascript side of node core

Back

es6 module syntax

Front

Back

System Events - from the C++ side of the node core via library called libuv

Front

events coming from the computer system: "I've finished reading the file" "the file is open" "I've received data from the internet we can then respond to those things happening with our code

Back

Module pattern: add new property to the exports object

Front

var greet2 = require(./greet2').greet;

Back

Section 3

(50 cards)

binary data

Front

bit - short for "binary digit" transistor - is electricity flowing or nah?

Back

character encoding

Front

the representation of characters on the keyboard with bytes, most having roots in the earliest standard, ASCII (American Standard Code for Information Interchange). from base10 to base2 !

Back

Callback

Front

this idea DOES exist in multiple languages, including C++

Back

EventEmitter.call(this)

Front

since it is passed by reference the EventEmitter will be called with this.greeting and the "this" object we make will definitely have all of the EventEmitter stuff as well as greeting

Back

Non-blocking

Front

node can go do something else while your javascript continues running when the v8 engine is no longer busy, then something can happen (?) having multiple sets of code running simultaneously is hard to manage node lets us write synchronous JS and pick up things that run asynchronously

Back

Chunks

Front

Back

es6 typed arrays (nothing to do with node, a new feature of v8)

Front

CAN deal with binary data nothing Int32 - a number stored with 32 0s and 1s can store 2 numbers in this view view here will let you put in regular base10 numbers but it will make binary again, node has nothing to do with this

Back

example of util.inherits WITH the importance of .call

Front

Person has this.firstname 'John' and a greet function the Policeman will be greeted with 'Hello undefined' "greet" is on the prototype, and THAT is connected up but the properties are not for that, you need .call to give context (the function constructor is never actually run, so he says)

Back

callback example with params / data

Front

Back

Libuv

Front

embedded inside node, handles system events manages events coming from the OS

Back

Abstract (Base) Class

Front

you never really make a new Stream you make some variable of stream

Back

2. libuv picks up something from its queue that is complete, processes it, sees that they thing has a callback

Front

callback involves running some javascript code node is async because both these things are going on at once, so he says... "event-driven non-blocking I/o in v8 javascript"

Back

unicode character set example

Front

Back

Buffer object (it's global! and in JS! not unlike using new Date( ) )

Front

created on c++ side, wrapped in JS buffer can hold binary data and will let us decode them

Back

data sits on the heap

Front

the memory space that the javascript engine is using - the buffer data sits there we need to minimize how much data we are working with at any one time instead the buffer

Back

class syntax with a function

Front

Back

character set

Front

A list of the characters and the codes used to represent each one

Back

Buffer

Front

just a spot in memory... gather some data, and move it along Buffer (usually) moves through stream

Back

objects can do things and...

Front

emit events, because they have the eventEmitter in their prototype chain

Back

.call can change the "this"

Front

run the function on whatever "this" you provide so you can send in another object entirely obj.greet( ) outputs "Hello John Doe" because of the internal object and obj.greet.call({name: 'Jane Doe'}) gives "Hello Jane Doe"

Back

stream.js - now there are several types of streams

Front

built on top of the eventEmitter streams are merely an abstract class...

Back

template literal

Front

you would have to convert this with babel in the browser, but node knows how to handle it

Back

fs.readSync

Front

var fs = require('fs'); var myFileContents = fs.readFileSync(__dirname + './myFile.text', 'utf8'); console.log(myFileContents);

Back

use jsconfig to make vscode not complain about es6 feature

Front

Back

util.inherits is extending EventEmitter

Front

create new objects that have a combination of new properties and inherited properties

Back

Stream

Front

speed of the stream may be impacted by, say, your internet connection speed usually as the stream runs, something gathers and processes it

Back

Synchronous

Front

v8 (javascript) is synchronous, but node is asynchronous

Back

buffers may be coming back from a feature within node...

Front

... but you rarely have to deal with them directly

Back

otherwise buffer behaves like an array console.log(buf[2])

Front

outputs 108 which is... l

Back

.apply is the same as .call but takes its params in an ARRAY (and params and the SECOND argument in both cases)

Front

obj.call({name: 'Jane'}, param1, param2, param3) obj.apply({name: 'Jane'}, [param1, param2, param3])

Back

var buf = new Buffer('Hello, 'utf8') console.log(buf)

Front

(utf8 is default anyway) outputs in hexadecimal notation (which is binary but easier to read)

Back

var buf = new Buffer('Hello, 'utf8'); console.log(buf); console.log(buf.toString( ) ); console.log(buf.toJSON( ) );

Front

string will put it back to 'Hello', JSON will build an JSON with 'type' and 'data' keys

Back

... use .call t get properties

Front

Person has this.firstname 'John' and a greet function Person.call(this) will send an empty object, a place to hold properties that allows first name to be attached to it ...then within Policeman badge number will ALSO be attached the Policeman will be greeted with 'Hello John'

Back

if you have many simultaneous users, you don't want to read synchronously (especially if the file is very large)

Front

var fs = require('fs'); var myOtherFileContents = fs.read(__dirname + './myOtherFile.text', function(err, data ) { <do something> }'utf8'); console.log(myFileContents); hey, c++, go do your thing and get file contents, the javascript that outputs it will run when you are done 'Done!' will run right after the sync fs is done, because it could, and THEN the async fs will finish

Back

can also add in parameters

Front

Back

class syntax with properties

Front

you still can call new Person(firstname, lastname)

Back

class syntax with the EventEmitter

Front

constructor doesn't have any params because we don't need any extends instead of util.inherits calling super( ) calls EventEmitter ensuring all its properties go onto the prototype greet function is put onto the prototype (SO class is building a prototype !)

Back

"buffering"

Front

gathering enough data until you can continue to, say, watch video

Back

Stream + Buffer

Front

data comes down the stream, a certain amount is gathered into the buffer, then that subset of data is processed, something is done with it when continue to get data until the stream is done

Back

utf8 - each character gets 8 bits to encode it, even if the unicode number doesn't make it look like it needs all of them

Front

set - what number represents each character encoding - how many numbers will we use to store it ... javascript isn't good at the encoding node expands on js to let us deal better with binary data

Back

callback simple example

Front

Back

1. libuv runs through its queue while, simultaneously, v8 is synchronously running

Front

Back

babeljs.io

Front

will let you write es6 in the browser

Back

Asynchronous

Front

Back

byte

Front

8 zeros and ones

Back

libuv

Front

asynchronous I/o made simple libuv.org written in c uv_run (in core.c) is its primary loop, checking for things to invoke, listening for events

Back

Error-First Callbacks

Front

a standard pattern by default a callback's first parameter is an error, and if there is no error it is "null"

Back

you can write to a buffer buf.write('wo') console.log(buf.toString( ) )

Front

..it will overwrite part of what would otherwise be there, it's a finite amount of space wollo

Back

class expression exported from a module, put it in greetr.js then call the constructor function

Front

var Greetr = require('./greetr'); var greeter1 = new Greetr( ); greeter1.on('greet, function(data) { console.log('someone greeted: ' + data) }); greeter.greet('Tony'); event is received and we get 'someone greeted: Tony'

Back

syntactic sugar

Front

Back

Section 4

(50 cards)

Routing

Front

choose to give different content based on different urls

Back

a more robust implementation of the read / write we wrote

Front

pipe returns its destination to us

Back

writeable stream - write from one file to another

Front

listen for the data event, then write didn't need a big buffer to work with the file

Back

port mapping to connect up to the right program

Front

we often specify 80 is a typical default (?)

Back

we think of node as being a web server...

Front

BUT you could use it to build a mail server, a file server, etc.

Back

Pipe

Front

Back

conditional logic on the req to route

Front

return different responses from '/' and '/api'

Back

Send template data to the html

Front

<h1>{Message}</h1> template engines aren't in the nodeJS core, but of course we know they exist externally

Back

stream to stream to stream - chaining

Front

node likes it when we work with streams, because it helps it be performant tend towards asynchronous methods and streams

Back

Endpoint

Front

Back

http.js ALSO wraps eventEmitter

Front

there is also https.js to deal with secure connections contains .createServer

Back

Package

Front

Back

machine code is running once you have started the server...

Front

so if you have made an update you need to restart the server every time you change content

Back

TCP is the same CONCEPT as a stream...

Front

... so node treats them as a stream

Back

send an html file

Front

Back

Protocol

Front

Back

see it come back as text but in smaller chunks (specify the buffer size) then measure the length of each chunk

Front

16384, 16384, 16384, 12456

Back

Patch

Front

Back

fs.js lets you look at a concrete implementation of stream, it makes a new ReadStream (a specialized type of readable stream)

Front

Back

_http_server.js wraps http_parser...

Front

and has the idea of status codes

Back

http

Front

Back

Serialize

Front

usually serialize "turn it into json" and deserialize "turn it back into a javascript object"

Back

now we know how to do everything for a web server but deal with databases...

Front

Back

socket

Front

the connection between two computers - with the internet, we are opening and closing them constantly a web socket is open all the time (?)

Back

http_parser

Front

a c program from joyent - parses requests and response the node js JavaScript side of the core has a wrapper for it

Back

use stream to get the html in a more performant way

Front

response is a writeable stream we have a readable file, pipe it into the response (sending it a chunk at a time in a stream)

Back

Dependency

Front

Back

zlib

Front

gzip is an algorithm to compress files zlib will do this compression for you

Back

Now we are closer to being able to have a web server...

Front

Back

Template

Front

Back

readableStream

Front

readable stream inherits from Stream readable is a type of stream... and also a type of event emitter... since stream is a type of event emitter

Back

outputting json - essentially an API endpoint

Front

any application in any language could come and grab the data from this url

Back

reading in a big file, a 'data' event will fire when the buffer fills up

Front

we can console out each chunk of data as the buffer fills

Back

neat read / write using pipe

Front

Back

Versioning

Front

the numbers MEAN something - that makes it "semantic" semver.org

Back

Method Chaining

Front

Back

Readable.prototype.pipe

Front

Back

socket opens between two ips

Front

tcp knows how to take information in one of the protocols (smtp, http, ftp) and send it over the socket

Back

Package Management

Front

Back

Mime type

Front

Back

http response example

Front

Back

port

Front

Back

prototype chain including stream

Front

Back

http request example with headers

Front

Back

== vs. ===

Front

== tries to convert one side to match the other, just in case - coercion!

Back

pipe from readable to readable&writeable

Front

Back

writeable and readable...

Front

... from node's perspective

Back

pipe from readable to writeable...

Front

Back

tcp sends info over a bit at a time, in packets

Front

node can create a socket and send information

Back

API

Front

Back

Section 5

(29 cards)

Environment Variables

Front

Back

Minor

Front

Back

nodemon

Front

has a "cli" folder, it's meant to be used in the cli restarts node for you

Back

Major

Front

Back

npm update

Front

checks for newer versions of my packages (as allowed) and overwrites them as necessary

Back

Static

Front

Back

application in express

Front

everything express is doing, you could have coded yourself in javascript

Back

Middleware

Front

there can be multiple levels of middleware app.use make the app use middleware express.static is middleware that catches requests and gets static files if needed expresses/recources/middleware for good third-party stuff

Back

dev dependencies

Front

packages you only need while building your app, not for running it

Back

express generator app layout

Front

Back

npm

Front

we could be speaking of the registry OR the program npm comes with node

Back

process.env

Front

'process' is a global variable provided by node process.env.PORT || 3000 is either the env variable or the default value 3000

Back

REST

Front

follow a good url structure and deal with http methods in a reasonable way

Back

http method

Front

exists inside the http req itself

Back

NoSQL

Front

sacrifice some hard drive space for a great deal of flexibility with your data

Back

req.query.SOMETHING

Front

will get you ?SOMETHING=somethingElse from the query string

Back

Querystring data

Front

appears in the url

Back

controllers

Front

in between the model and the view

Back

default express generator dependencies

Front

Back

Querystring in a post

Front

Back

app.use just matches a route and then takes a function, then you call next

Front

express provides next to your callback so it will call the next middleware I can do whatever I want with the req and res if you don't provide a route it will match ALL requests that come in

Back

even though it is tabular data, mysql and similar libraries should return...

Front

...arrays of object

Back

pulling specific patterns out of the routes

Front

...with pattern matching

Back

caret

Front

any minor or patch update within this major version is ok

Back

express has a lot of methods on it

Front

Back

tilde

Front

only give me patch update

Back

using mysql data

Front

it will be converted to javascript objects mysql library is a mysql driver put the connection in the middleware...

Back

body-parser urlencoded will put your values on the req.body object

Front

then you can access them with req.body.<key>

Back

mongolab

Front

small free mongo storage

Back