Skip to content

Instantly share code, notes, and snippets.

@y4rr
Forked from ui2code/.cheasheets.md
Created January 7, 2021 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save y4rr/499ea25961e6fe993dad65c5be97cada to your computer and use it in GitHub Desktop.
Save y4rr/499ea25961e6fe993dad65c5be97cada to your computer and use it in GitHub Desktop.
Cheatsheets

Bash

Getting started

Example

#!/usr/bin/env bash

NAME="John"
echo "Hello $NAME!"

Variables

NAME="John"
echo $NAME
echo "$NAME"
echo "${NAME}!"

String quotes

NAME="John"
echo "Hi $NAME"  #=> Hi John
echo 'Hi $NAME'  #=> Hi $NAME

Shell execution

echo "I'm in $(pwd)"
echo "I'm in `pwd`"
# Same

See Command substitution

Conditional execution

git commit && git push
git commit || echo "Commit failed"

Functions

get_name() {
  echo "John"
}

echo "You are $(get_name)"

See: Functions

Conditionals

if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
fi

See: Conditionals

Strict mode

set -euo pipefail
IFS=$'\n\t'

See: Unofficial bash strict mode

Brace expansion

echo {A,B}.js

| {A,B} | Same as A B | | {A,B}.js | Same as A.js B.js | | {1..5} | Same as 1 2 3 4 5 |

See: Brace expansion

Parameter expansions

Basics

name="John"
echo ${name}
echo ${name/J/j}    #=> "john" (substitution)
echo ${name:0:2}    #=> "Jo" (slicing)
echo ${name::2}     #=> "Jo" (slicing)
echo ${name::-1}    #=> "Joh" (slicing)
echo ${name:(-1)}   #=> "n" (slicing from right)
echo ${name:(-2):1} #=> "h" (slicing from right)
echo ${food:-Cake}  #=> $food or "Cake"
length=2
echo ${name:0:length}  #=> "Jo"

See: Parameter expansion

STR="/path/to/foo.cpp"
echo ${STR%.cpp}    # /path/to/foo
echo ${STR%.cpp}.o  # /path/to/foo.o

echo ${STR##*.}     # cpp (extension)
echo ${STR##*/}     # foo.cpp (basepath)

echo ${STR#*/}      # path/to/foo.cpp
echo ${STR##*/}     # foo.cpp

echo ${STR/foo/bar} # /path/to/bar.cpp
STR="Hello world"
echo ${STR:6:5}   # "world"
echo ${STR:-5:5}  # "world"
SRC="/path/to/foo.cpp"
BASE=${SRC##*/}   #=> "foo.cpp" (basepath)
DIR=${SRC%$BASE}  #=> "/path/to/" (dirpath)

Substitution

Code Description
${FOO%suffix} Remove suffix
${FOO#prefix} Remove prefix
--- ---
${FOO%%suffix} Remove long suffix
${FOO##prefix} Remove long prefix
--- ---
${FOO/from/to} Replace first match
${FOO//from/to} Replace all
--- ---
${FOO/%from/to} Replace suffix
${FOO/#from/to} Replace prefix

Comments

# Single line comment
: '
This is a
multi line
comment
'

Substrings

| ${FOO:0:3} | Substring (position, length) | | ${FOO:-3:3} | Substring from the right |

Length

| ${#FOO} | Length of $FOO |

Manipulation

STR="HELLO WORLD!"
echo ${STR,}   #=> "hELLO WORLD!" (lowercase 1st letter)
echo ${STR,,}  #=> "hello world!" (all lowercase)

STR="hello world!"
echo ${STR^}   #=> "Hello world!" (uppercase 1st letter)
echo ${STR^^}  #=> "HELLO WORLD!" (all uppercase)

Default values

| ${FOO:-val} | $FOO, or val if not set | | ${FOO:=val} | Set $FOO to val if not set | | ${FOO:+val} | val if $FOO is set | | ${FOO:?message} | Show error message and exit if $FOO is not set |

The : is optional (eg, ${FOO=word} works)

Loops

Basic for loop

for i in /etc/rc.*; do
  echo $i
done

C-like for loop

for ((i = 0 ; i < 100 ; i++)); do
  echo $i
done

Ranges

for i in {1..5}; do
    echo "Welcome $i"
done

With step size

for i in {5..50..5}; do
    echo "Welcome $i"
done

Reading lines

cat file.txt | while read line; do
  echo $line
done

Forever

while true; do
  ···
done

Functions

Defining functions

myfunc() {
    echo "hello $1"
}
# Same as above (alternate syntax)
function myfunc() {
    echo "hello $1"
}
myfunc "John"

Returning values

myfunc() {
    local myresult='some value'
    echo $myresult
}
result="$(myfunc)"

Raising errors

myfunc() {
  return 1
}
if myfunc; then
  echo "success"
else
  echo "failure"
fi

Arguments

Expression Description
$# Number of arguments
$* All arguments
$@ All arguments, starting from first
$1 First argument
$_ Last argument of the previous command

See Special parameters.

Conditionals

Conditions

Note that [[ is actually a command/program that returns either 0 (true) or 1 (false). Any program that obeys the same logic (like all base utils, such as grep(1) or ping(1)) can be used as condition, see examples.

Condition Description
[[ -z STRING ]] Empty string
[[ -n STRING ]] Not empty string
[[ STRING == STRING ]] Equal
[[ STRING != STRING ]] Not Equal
--- ---
[[ NUM -eq NUM ]] Equal
[[ NUM -ne NUM ]] Not equal
[[ NUM -lt NUM ]] Less than
[[ NUM -le NUM ]] Less than or equal
[[ NUM -gt NUM ]] Greater than
[[ NUM -ge NUM ]] Greater than or equal
--- ---
[[ STRING =~ STRING ]] Regexp
--- ---
(( NUM < NUM )) Numeric conditions
Condition Description
[[ -o noclobber ]] If OPTIONNAME is enabled
--- ---
[[ ! EXPR ]] Not
[[ X ]] && [[ Y ]] And
`[[ X ]]

File conditions

Condition Description
[[ -e FILE ]] Exists
[[ -r FILE ]] Readable
[[ -h FILE ]] Symlink
[[ -d FILE ]] Directory
[[ -w FILE ]] Writable
[[ -s FILE ]] Size is > 0 bytes
[[ -f FILE ]] File
[[ -x FILE ]] Executable
--- ---
[[ FILE1 -nt FILE2 ]] 1 is more recent than 2
[[ FILE1 -ot FILE2 ]] 2 is more recent than 1
[[ FILE1 -ef FILE2 ]] Same files

Example

# String
if [[ -z "$string" ]]; then
  echo "String is empty"
elif [[ -n "$string" ]]; then
  echo "String is not empty"
fi
# Combinations
if [[ X ]] && [[ Y ]]; then
  ...
fi
# Equal
if [[ "$A" == "$B" ]]
# Regex
if [[ "A" =~ . ]]
if (( $a < $b )); then
   echo "$a is smaller than $b"
fi
if [[ -e "file.txt" ]]; then
  echo "file exists"
fi

Arrays

Defining arrays

Fruits=('Apple' 'Banana' 'Orange')
Fruits[0]="Apple"
Fruits[1]="Banana"
Fruits[2]="Orange"

Working with arrays

echo ${Fruits[0]}           # Element #0
echo ${Fruits[@]}           # All elements, space-separated
echo ${#Fruits[@]}          # Number of elements
echo ${#Fruits}             # String length of the 1st element
echo ${#Fruits[3]}          # String length of the Nth element
echo ${Fruits[@]:3:2}       # Range (from position 3, length 2)

Operations

Fruits=("${Fruits[@]}" "Watermelon")    # Push
Fruits+=('Watermelon')                  # Also Push
Fruits=( ${Fruits[@]/Ap*/} )            # Remove by regex match
unset Fruits[2]                         # Remove one item
Fruits=("${Fruits[@]}")                 # Duplicate
Fruits=("${Fruits[@]}" "${Veggies[@]}") # Concatenate
lines=(`cat "logfile"`)                 # Read from file

Iteration

for i in "${arrayName[@]}"; do
  echo $i
done

Dictionaries

Defining

declare -A sounds
sounds[dog]="bark"
sounds[cow]="moo"
sounds[bird]="tweet"
sounds[wolf]="howl"

Declares sound as a Dictionary object (aka associative array).

Working with dictionaries

echo ${sounds[dog]} # Dog's sound
echo ${sounds[@]}   # All values
echo ${!sounds[@]}  # All keys
echo ${#sounds[@]}  # Number of elements
unset sounds[dog]   # Delete dog

Iteration

Iterate over values

for val in "${sounds[@]}"; do
  echo $val
done

Iterate over keys

for key in "${!sounds[@]}"; do
  echo $key
done

Options

Options

set -o noclobber  # Avoid overlay files (echo "hi" > foo)
set -o errexit    # Used to exit upon error, avoiding cascading errors
set -o pipefail   # Unveils hidden failures
set -o nounset    # Exposes unset variables

Glob options

shopt -s nullglob    # Non-matching globs are removed  ('*.foo' => '')
shopt -s failglob    # Non-matching globs throw errors
shopt -s nocaseglob  # Case insensitive globs
shopt -s dotglob     # Wildcards match dotfiles ("*.sh" => ".foo.sh")
shopt -s globstar    # Allow ** for recursive matches ('lib/**/*.rb' => 'lib/a/b/c.rb')

Set GLOBIGNORE as a colon-separated list of patterns to be removed from glob matches.

History

Commands

| history | Show history | | shopt -s histverify | Don't execute expanded result immediately |

Expansions

| !$ | Expand last parameter of most recent command | | !* | Expand all parameters of most recent command | | !-n | Expand nth most recent command | | !n | Expand nth command in history | | !<command> | Expand most recent invocation of command <command> |

Operations

| !! | Execute last command again |
| !!:s/<FROM>/<TO>/ | Replace first occurrence of <FROM> to <TO> in most recent command | | !!:gs/<FROM>/<TO>/ | Replace all occurrences of <FROM> to <TO> in most recent command | | !$:t | Expand only basename from last parameter of most recent command | | !$:h | Expand only directory from last parameter of most recent command |

!! and !$ can be replaced with any valid expansion.

Slices

| !!:n | Expand only nth token from most recent command (command is 0; first argument is 1) | | !^ | Expand first argument from most recent command | | !$ | Expand last token from most recent command | | !!:n-m | Expand range of tokens from most recent command | | !!:n-$ | Expand nth token to last from most recent command |

!! can be replaced with any valid expansion i.e. !cat, !-2, !42, etc.

Miscellaneous

Numeric calculations

$((a + 200))      # Add 200 to $a
$((RANDOM%=200))  # Random number 0..200

Subshells

(cd somedir; echo "I'm now in $PWD")
pwd # still in first directory

Redirection

python hello.py > output.txt   # stdout to (file)
python hello.py >> output.txt  # stdout to (file), append
python hello.py 2> error.log   # stderr to (file)
python hello.py 2>&1           # stderr to stdout
python hello.py 2>/dev/null    # stderr to (null)
python hello.py &>/dev/null    # stdout and stderr to (null)
python hello.py < foo.txt      # feed foo.txt to stdin for python

Inspecting commands

command -V cd
#=> "cd is a function/alias/whatever"

Trap errors

trap 'echo Error at about $LINENO' ERR

or

traperr() {
  echo "ERROR: ${BASH_SOURCE[1]} at about ${BASH_LINENO[0]}"
}

set -o errtrace
trap traperr ERR

Case/switch

case "$1" in
  start | up)
    vagrant up
    ;;

  *)
    echo "Usage: $0 {start|stop|ssh}"
    ;;
esac

Source relative

source "${0%/*}/../share/foo.sh"

printf

printf "Hello %s, I'm %s" Sven Olga
#=> "Hello Sven, I'm Olga

printf "1 + 1 = %d" 2
#=> "1 + 1 = 2"

printf "This is how you print a float: %f" 2
#=> "This is how you print a float: 2.000000"

Directory of script

DIR="${0%/*}"

Getting options

while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in
  -V | --version )
    echo $version
    exit
    ;;
  -s | --string )
    shift; string=$1
    ;;
  -f | --flag )
    flag=1
    ;;
esac; shift; done
if [[ "$1" == '--' ]]; then shift; fi

Heredoc

cat <<END
hello world
END

Reading input

echo -n "Proceed? [y/n]: "
read ans
echo $ans
read -n 1 ans    # Just one character

Special variables

| $? | Exit status of last task | | $! | PID of last background task | | $$ | PID of shell | | $0 | Filename of the shell script |

See Special parameters.

Go to previous directory

pwd # /home/user/foo
cd bar/
pwd # /home/user/foo/bar
cd -
pwd # /home/user/foo

Check for command's result

if ping -c 1 google.com; then
  echo "It appears you have a working internet connection"
fi

Grep check

if grep -q 'foo' ~/.bash_history; then
  echo "You appear to have typed 'foo' in the past"
fi

Also see

CSS

Basics

Selectors

.class {
  font-weight: bold;
}
Selector Description
* All elements
div Element
.class Class
#id ID
[disabled] Attribute
[role="dialog"] Attribute

Combinators

Selector Description
.parent .child Descendant
.parent > .child Direct descendant
.child + .sibling Adjacent sibling
.child ~ .sibling Far sibling
.class1.class2 Have both classes

Attribute selectors

Selector Description
[role="dialog"] = Exact
[class~="box"] ~= Has word
`[class ="box"]`
[href$=".doc"] $= Ends in
[href^="/index"] ^= Begins with
[class*="-is-"] *= Contains

Pseudo-classes

Selector Description
:target eg, h2#foo:target
--- ---
:disabled
:focus
:active
--- ---
:nth-child(3) 3rd child
:nth-child(3n+2) 2nd child in groups of 3
:nth-child(-n+4)
--- ---
:nth-last-child(2)
:nth-of-type(2)
--- ---
:checked Checked inputs
:disabled Disabled elements
:default Default element in a group
--- ---
:empty Elements without children

Pseudo-class variations

Selector
:first-of-type
:last-of-type
:nth-of-type(2)
:only-of-type
---
:first-child
:last-child
:nth-child(2)
:only-child

Fonts

Properties

Property Description
font-family: <font>, <fontN>
font-size: <size>
letter-spacing: <size>
line-height: <number>
--- ---
font-weight: bold normal
font-style: italic normal
text-decoration: underline none
--- ---
text-align: left right center justify
text-transform: capitalize uppercase lowercase

Shorthand

style weight size (required) line-height family
font: italic 400 14px / 1.5 sans-serif
style weight size (required) line-height family (required)

Example

font-family: Arial;
font-size: 12pt;
line-height: 1.5;
letter-spacing: 0.02em;
color: #aa3322;

Case

text-transform: capitalize; /* Hello */
text-transform: uppercase; /* HELLO */
text-transform: lowercase; /* hello */

Background

Properties

Property Description
background: (Shorthand)
--- ---
background-color: <color>
background-image: url(...)
background-position: left/center/right top/center/bottom
background-size: cover X Y
background-clip: border-box padding-box content-box
background-repeat: no-repeat repeat-x repeat-y
background-attachment: scroll fixed local

Shorthand

color image positionX positionY size repeat attachment
background: #ff0 url(bg.jpg) left top / 100px auto no-repeat fixed;
background: #abc url(bg.png) center center / cover repeat-x local;
color image positionX positionY size repeat attachment

Multiple backgrounds

background: linear-gradient(to bottom, rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
  url('background.jpg') center center / cover, #333;

Animation

Properties

Property Value
animation: (shorthand)
animation-name: <name>
animation-duration: <time>ms
animation-timing-function: ease linear ease-in ease-out ease-in-out
animation-delay: <time>ms
animation-iteration-count: infinite <number>
animation-direction: normal reverse alternate alternate-reverse
animation-fill-mode: none forwards backwards both initial inherit
animation-play-state: normal reverse alternate alternate-reverse

Shorthand

name duration timing-function delay count direction fill-mode play-state
animation: bounce 300ms linear 100ms infinite alternate-reverse both reverse
name duration timing-function delay count direction fill-mode play-state

Example

animation: bounce 300ms linear 0s infinite normal;
animation: bounce 300ms linear infinite;
animation: bounce 300ms linear infinite alternate-reverse;
animation: bounce 300ms linear 2s infinite alternate-reverse forwards normal;

Event

.one('webkitAnimationEnd oanimationend msAnimationEnd animationend')

Docker

Manage images

docker build

docker build [options] .
  -t "app/container_name"    # name
  --build-arg APP_HOME=$APP_HOME    # Set build-time variables

Create an image from a Dockerfile.

docker run

docker run [options] IMAGE
  # see `docker create` for options

Example

$ docker run -it debian:buster /bin/bash

Run a command in an image.

Manage containers

docker create

docker create [options] IMAGE
  -a, --attach               # attach stdout/err
  -i, --interactive          # attach stdin (interactive)
  -t, --tty                  # pseudo-tty
      --name NAME            # name your image
  -p, --publish 5000:5000    # port map
      --expose 5432          # expose a port to linked containers
  -P, --publish-all          # publish all ports
      --link container:alias # linking
  -v, --volume `pwd`:/app    # mount (absolute paths needed)
  -e, --env NAME=hello       # env vars

Example

$ docker create --name app_redis_1 \
  --expose 6379 \
  redis:3.0.2

Create a container from an image.

docker exec

docker exec [options] CONTAINER COMMAND
  -d, --detach        # run in background
  -i, --interactive   # stdin
  -t, --tty           # interactive

Example

$ docker exec app_web_1 tail logs/development.log
$ docker exec -t -i app_web_1 rails c

Run commands in a container.

docker start

docker start [options] CONTAINER
  -a, --attach        # attach stdout/err
  -i, --interactive   # attach stdin

docker stop [options] CONTAINER

Start/stop a container.

docker ps

$ docker ps
$ docker ps -a
$ docker kill $ID

Manage containers using ps/kill.

docker logs

$ docker logs $ID
$ docker logs $ID 2>&1 | less
$ docker logs -f $ID # Follow log output

See what's being logged in an container.

Images

docker images

$ docker images
  REPOSITORY   TAG        ID
  ubuntu       12.10      b750fe78269d
  me/myapp     latest     7b2431a8d968
$ docker images -a   # also show intermediate

Manages images.

docker rmi

docker rmi b750fe78269d

Deletes images.

Clean up

Clean all

docker system prune

Cleans up dangling images, containers, volumes, and networks (ie, not associated with a container)

docker system prune -a

Additionally remove any stopped containers and all unused images (not just dangling images)

Containers

# Stop all running containers
docker stop $(docker ps -a -q)

# Delete stopped containers
docker container prune

Images

docker image prune [-a]

Delete all the images

Volumes

docker volume prune

Delete all the volumes

Also see

git init # initiates git in the current directory
git clone <address> # creates a git repo from given address (get the address from your git-server)
git add file.txt # adds(stages) file.txt to the git
git add * # adds(stages) all new modifications, deletions, creations to the git
git reset file.txt # Removes file.txt from the stage
git rm file.txt # removes file.txt both from git and file system
git status # shows the modifications and stuff that are not staged yet
git branch # shows all the branches (current branch is shown with a star)
git branch my-branch # creates my-branch
git branch -d my-branch # deletes my-branch
git checkout my-bracnch # switches to my-branch
git merge my-branch # merges my-branch to current branch
git push origin :my-branch # delete remote branch
git cherry-pick <commit_id> # merge the specified commit
git remote # shows the remotes
git remote -v # shows the remote for pull and push
git remote add my-remote <address> # creates a remote (get the address from your git-server)
git log # shows the log of commits
git commit -m "msg" # commit changes with a msg
git push my-remote my-branch # pushes the commits to the my-remote in my-branch (does not push the tags)
git tag # shows all the tags
git tag -a v1.0 -m "msg" # creates an annotated tag
git show v1.0 # shows the description of version-1.0 tag
git tag --delete v1.0 # deletes the tag in local directory
git push --delete my-remote v1.0 # deletes the tag in my-remote (be carefore to not delete a branch)
git push my-remote my-branch v1.0 # push v1.0 tag to my-remote in my-branch
git fetch --tags # pulls the tags from remote
git pull my-remote my-branch # pulls and tries to merge my-branch from my-remote to the current branch
git stash # stashes the staged and unstaged changes (git status will be clean after it)
git stash -u # stash everything including new untracked files (but not .gitignore)
git stash save "msg" # stash with a msg
git stash list # list all stashes
git stash pop # delete the recent stash and applies it
git stash stach@{2} # delete the {2} stash and applies it
git stash show # shows the description of stash
git stash apply # keep the stash and applies it to the git
git stash branch my-branch stash@{1} # creates a branch from your stash
git stash drop stash@{1} # deletes the {1} stash
git stash clear # clears all the stash
.gitignore
# is a file including names of stuff that you don"t want to be staged or tracked.
# You usually keep your local files like database, media, and etc here.
# You can find good resources online about ignoring specific files in your project files.
# .gitignore is also get ignored
.git
# is a hidden directory in repo directory including git files. It is created after "git init".
<!-- * *******************************************************************************************
* HTML5 Cheat sheet by Hackr.io
* Source: https://websitesetup.org/wp-content/uploads/2014/02/HTML-CHEAT-SHEET-768x8555.png
* ******************************************************************************************* * -->
<!-- Document Summary -->
<!DOCTYPE html> <!-- Tells the browser that HTML5 version of HTML to be recognized by the browser -->
<html lang="en"></html> <!-- The HTML lang attribute is used to identify the language of text content on the web. This information helps search engines return language specific results, -->
<head></head> <!-- Contains Information specific to the page like title, styles and scripts -->
<title></title> <!-- Title for the page that shows up in the browser title bar -->
<body></body> <!-- Content that the user will see -->
<!-- Document Information -->
<base/> <!-- Usefull for specifying relative links in a document -->
<style></style> <!-- Contains styles for the html document -->
<meta/> <!-- Contains additional information about the page, author, page description and other hidden page info -->
<script></script> <!-- Contains all scripts internal or external -->
<link/> <!-- Used to create relationships with external pages and stylesheets -->
<!-- Document Structure -->
<h1></h1> ... <h6></h6> <!-- All six levels of heading with 1 being the most promiment and 6 being the least prominent -->
<p></p> <!-- Used to organize paragraph text -->
<div></div> <!-- A generic container used to denote a page section -->
<span></span> <!-- Inline section or block container used for creating inline style elements -->
<br/> <!-- Creates a line-break -->
<hr> <!-- Creates a sectional break into HTML -->
<!-- Text Formatting -->
<strong></strong> and <b></b> <!-- Makes text contained in the tag as bold -->
<em></em> and <i></i> <!-- Alternative way to make the text contained in the tag as italic -->
<strike></strike> <!-- Creates a strike through the text element -->
<pre></pre> <!-- Preformatted monospace text block with some spacing intact -->
<blockquote></blockquote> <!-- Contains long paragraphs of quotations often cited -->
<abbr></abbr> <!-- Contains abbreviations while also making the full form avaialable -->
<address></address> <!-- Used to display contact information -->
<code></code> <!-- Used to display inline code snippets -->
<!-- Links Formatting -->
<a href="url"></a> <!-- Used to link to external or internal pages of a wbesite -->
<a href="mailto:email@example.com"></a> <!-- Used to link to an email address -->
<a href="name"></a> <!-- Used to link to a document element -->
<a href="#name"></a> <!-- Used to link to specific div element -->
<a href="tel://####-####-##"></a> <!-- Used to display phone numbers and make them clickable -->
<!-- Image Formatting -->
<img src="url" alt="text"> <!-- Used to display images in a webpage where src="url" contains the link to the image source and alt="" contains an alternative text to display when the image is not displayed -->
<!-- List Formatting -->
<ol></ol> <!-- Used to create ordered lists with numbers in the items -->
<ul></ul> <!-- Used to display unordered lists with numbers in the items -->
<li></li> <!-- Contains list items inside ordered and unordered lists -->
<dl></dl> <!-- Contains list item definitions -->
<dt></dt> <!-- Definition of single term inline with body content -->
<dd></dd> <!-- The descrpition of the defined term -->
<!-- Forms Formatting and Attributes -->
<form action="url"></form> <!-- Form element creates a form and action="" specifies where the data is to be sent to when the visitor submits the form -->
<!-- Supported attributes -->
method="somefunction()" <!-- Contains the type of request (GET, POST... etc) which dictates how to send the data of the form -->
enctype="" <!-- Dictates how the data is to be encoded when the data is sent to the web server. -->
autocomplete="" <!-- Specifies if the autocomplete functionality is enabled or not -->
novalidate <!-- Dictates if the form will be validated or not -->
accept-charset="" <!-- Identifies the character encoding upon form submission -->
target="" <!-- Tell where to display the information upon form submission. Possible values: '_blank', '_self', '_parent', '_top' -->
<fieldset disabled="disabled"></fieldset> <!-- Identifies the group of all fields in the form -->
<label for=""></label> <!-- A simple field label telling the user what to type in the field -->
<legend></legend> <!-- The form legend acts as a caption for the fieldset element -->
<input type="text/email/number/color/date"> <!-- Input is the input field where the user can input various types of data -->
<!-- Supported attributes -->
name="" <!-- Describes the name of the form -->
width="" <!-- Specifies the width of an input field -->
value="" <!-- Describes the value of the input information field -->
size="" <!-- Specifies the input element width in characters -->
maxlength="" <!-- Specifies the maximum input character numbers -->
required="" <!-- Specifies if the input field is required to fill in before submitting the form -->
step="" <!-- Identifies the legal number intervals of the input field -->
<textarea name="" id="" cols="30" rows="10"> <!-- Specifies a large input text field for longer messages -->
</textarea>
<select name=""></select> <!-- Describes a dropdown box for users to select from variety of choices -->
<!-- Supported attributes -->
name="" <!-- The name for a dropdown combination box -->
size="" <!-- Specifies the number of available options -->
multiple <!-- Allows for multiple option selections -->
required <!-- Requires that a value is selected before submitting the form -->
autofocus <!-- Specifies that the dropdown automatically comes to focus once the page loads -->
<optgroup></optgroup> <!-- Specifies the entire grouping of available options -->
<option value=""></option> <!-- Defines one of the avaialble option from the dropdown list -->
<button></button> <!-- A clickable button to submit the form -->
<!-- Tables Formatting -->
<table></table> <!-- Defines and contains all table related content -->
<caption></caption> <!-- A description of what table is and what it contains -->
<thead></thead> <!-- The table headers contain the type of information defined in each column underneath -->
<tbody></tbody> <!-- Contains the tables data or information -->
<tfoot></tfoot> <!-- Defines table footer -->
<tr></tr> <!-- Contains the information to be included in a table row -->
<th></th> <!-- Contains the information to be included in a single table header -->
<td></td> <!-- Contains actual information in a table cell -->
<colgroup></colgroup> <!-- Groups a single or multiple columns for formatting purposes -->
<col> <!-- Defines a single column of information inside a table -->
<!-- Objects and iFrames -->
<object data=""></object> <!-- Describes and embed file type including audio, video, PDF's, images -->
<!-- Supported attributes -->
type="" <!-- Describes the type of media embedded -->
height="" <!-- Describes the height of the object in pixels -->
width="" <!-- Describes the width of the object in pixels -->
usemap="" <!-- This is the name of the client-side image map in the object -->
<iframe src="" frameborder="0"></iframe> <!-- Contains an inline frame that allows to embed external information -->
<embed src="" type=""> <!-- Acts as a container for external application or plug-in -->
src="" <!-- The source of the external file you're embedding -->
width="" <!-- Describes the width of the iframe in pixels -->
<!-- HTML5 New Tags -->
<header></header> <!-- Defines the header block for a document or a section -->
<footer></footer> <!-- Defines the footer block for a document or a section -->
<main></main> <!-- Describes the main content of a document -->
<article></article> <!-- Identifies an article inside a document -->
<aside></aside> <!-- Specifies content contained in a document sidebar -->
<section></section> <!-- Defines a section of a document -->
<details></details> <!-- Describes additonal information that user can view or hide -->
<dialog></dialog> <!-- A dialog box or a window -->
<figure></figure> <!-- An independent content block featuring images, diagrams or illustrations -->
<figcaption></figcaption> <!-- Caption that describe a figure -->
<mark></mark> <!-- Displays a portion of highlighted text with in a page content -->
<nav></nav> <!-- Navigation links for the user in a document -->
<menuitem></menuitem> <!-- The specific menu item that a usrr can raise from a pop up menu -->
<meter></meter> <!-- Describes the scalar measurement with in a known array -->
<progress></progress> <!-- Displays the progress of a task usually a progress bar -->
<rp></rp> <!-- Describes text within the browsers that do not support ruby notations -->
<rt></rt> <!-- Displays east asian typography character details -->
<ruby></ruby> <!-- Describes annotations for east asian typography -->
<summary></summary> <!-- Contains a visible heading for details element -->
<bdi></bdi> <!-- Helps you format parts of text in a different direction than other text -->
<time></time> <!-- Identifies the time and date -->
<wbr> <!-- A line break within the content -->
<!-- Collective Character Objects -->
&#34; &quot; Quotation Marks - "
&#38; &amp; Ampersand - &
&#60; &lt; Less than sign - <
&#62; &gt; Greater than sign - >
&#160; &nbsp; Non-breaking space
&#169; &copy; Copyright Symbol - ©
&#64; &Uuml; @ symbol - @
&#149; &ouml; Small bullet - .
&#153; &ucirc; Trademark Symbol - ™
/* *******************************************************************************************
* GLOBAL OBJECTS > OBJECT
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
* ******************************************************************************************* */
// Global object: properties
Object.length // length is a property of a function object, and indicates how many arguments the function expects, i.e. the number of formal parameters. This number does not include the rest parameter. Has a value of 1.
Object.prototype // Represents the Object prototype object and allows to add new properties and methods to all objects of type Object.
// Methods of the Object constructor
Object.assign(target, ...sources) // Copies the values of all enumerable own properties from one or more source objects to a target object. method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object
Object.create(MyObject) // Creates a new object with the specified prototype object and properties. The object which should be the prototype of the newly-created object.
Object.defineProperty(obj, prop, descriptor) // Adds the named property described by a given descriptor to an object.
Object.defineProperties(obj, props) // Adds the named properties described by the given descriptors to an object.
Object.entries(obj) // Returns an array containing all of the [key, value] pairs of a given object's own enumerable string properties.
Object.freeze(obj) // Freezes an object: other code can't delete or change any properties.
Object.getOwnPropertyDescriptor(obj, prop) // Returns a property descriptor for a named property on an object.
Object.getOwnPropertyDescriptors(obj) // Returns an object containing all own property descriptors for an object.
Object.getOwnPropertyNames(obj) // Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
Object.getOwnPropertySymbols(obj) // Returns an array of all symbol properties found directly upon a given object.
Object.getPrototypeOf(obj) // Returns the prototype of the specified object.
Object.is(value1, value2); // Compares if two values are the same value. Equates all NaN values (which differs from both Abstract Equality Comparison and Strict Equality Comparison).
Object.isExtensible(obj) // Determines if extending of an object is allowed.
Object.isFrozen(obj) // Determines if an object was frozen.
Object.isSealed(obj) // Determines if an object is sealed.
Object.keys(obj) // Returns an array containing the names of all of the given object's own enumerable string properties.
Object.preventExtensions(obj) // Prevents any extensions of an object.
Object.seal(obj) // Prevents other code from deleting properties of an object.
Object.setPrototypeOf(obj, prototype) // Sets the prototype (i.e., the internal [[Prototype]] property).
Object.values(obj) // Returns an array containing the values that correspond to all of a given object's own enumerable string properties.
// Object instances and Object prototype object (Object.prototype.property or Object.prototype.method())
// Properties
obj.constructor // Specifies the function that creates an object's prototype.
obj.__proto__ // Points to the object which was used as prototype when the object was instantiated.
// Methods
obj.hasOwnProperty(prop) // Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
prototypeObj.isPrototypeOf(object) // Returns a boolean indicating whether the object this method is called upon is in the prototype chain of the specified object.
obj.propertyIsEnumerable(prop) // Returns a boolean indicating if the internal ECMAScript [[Enumerable]] attribute is set.
obj.toLocaleString() // Calls toString().
obj.toString() // Returns a string representation of the object.
object.valueOf() // Returns the primitive value of the specified object.
/* *******************************************************************************************
* GLOBAL OBJECTS > ARRAY
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
* ******************************************************************************************* */
// Global object: properties
Array.length // Reflects the number of elements in an array.
Array.prototype // Represents the prototype for the Array constructor and allows to add new properties and methods to all Array objects.
// Global object: methods
Array.from(arrayLike[, mapFn[, thisArg]]) // Creates a new Array instance from an array-like or iterable object.
Array.isArray(obj) // Returns true if a variable is an array, if not false.
Array.of(element0[, element1[, ...[, elementN]]]) // Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.
// Instance: properties
arr.length // Reflects the number of elements in an array.
// Instance: mutator methods
arr.copyWithin(target, start, end) // Copies a sequence of array elements within the array.
arr.fill(value, start, end) // Fills all the elements of an array from a start index to an end index with a static value.
arr.pop() // Removes the last element from an array and returns that element.
arr.push([element1[, ...[, elementN]]]) // Adds one or more elements to the end of an array and returns the new length of the array.
arr.reverse() // Reverses the order of the elements of an array in place — the first becomes the last, and the last becomes the first.
arr.shift() // Removes the first element from an array and returns that element.
arr.sort() // Sorts the elements of an array in place and returns the array.
array.splice(start, deleteCount, item1, item2, ...) // Adds and/or removes elements from an array.
arr.unshift([element1[, ...[, elementN]]]) // Adds one or more elements to the front of an array and returns the new length of the array.
// Instance: accessor methods
arr.concat(value1[, value2[, ...[, valueN]]]) // Returns a new array comprised of this array joined with other array(s) and/or value(s).
arr.includes(searchElement, fromIndex) // Determines whether an array contains a certain element, returning true or false as appropriate.
arr.indexOf(searchElement[, fromIndex]) // Returns the first (least) index of an element within the array equal to the specified value, or -1 if none is found.
arr.join(separator) // Joins all elements of an array into a string.
arr.lastIndexOf(searchElement, fromIndex) // Returns the last (greatest) index of an element within the array equal to the specified value, or -1 if none is found.
arr.slice(begin, end) // Extracts a section of an array and returns a new array.
arr.toString() // Returns a string representing the array and its elements. Overrides the Object.prototype.toString() method.
arr.toLocaleString(locales, options) // Returns a localized string representing the array and its elements. Overrides the Object.prototype.toLocaleString() method.
// Instance: iteration methods
arr.entries() // Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
arr.every(callback[, thisArg]) // Returns true if every element in this array satisfies the provided testing function.
arr.filter(callback[, thisArg]) // Creates a new array with all of the elements of this array for which the provided filtering function returns true.
arr.find(callback[, thisArg]) // Returns the found value in the array, if an element in the array satisfies the provided testing function or undefined if not found.
arr.findIndex(callback[, thisArg]) // Returns the found index in the array, if an element in the array satisfies the provided testing function or -1 if not found.
arr.forEach(callback[, thisArg]) // Calls a function for each element in the array.
arr.keys() // Returns a new Array Iterator that contains the keys for each index in the array.
arr.map(callback[, initialValue]) // Creates a new array with the results of calling a provided function on every element in this array.
arr.reduce(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.
arr.reduceRight(callback[, initialValue]) // Apply a function against an accumulator and each value of the array (from right-to-left) as to reduce it to a single value.
arr.some(callback[, initialValue]) // Returns true if at least one element in this array satisfies the provided testing function.
arr.values() // Returns a new Array Iterator object that contains the values for each index in the array.
/* *******************************************************************************************
* SYNOPSIS
* http://nodejs.org/api/synopsis.html
* ******************************************************************************************* */
var http = require('http');
// An example of a web server written with Node which responds with 'Hello World'.
// To run the server, put the code into a file called example.js and execute it with the node program.
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');
/* *******************************************************************************************
* GLOBAL OBJECTS
* http://nodejs.org/api/globals.html
* ******************************************************************************************* */
// In browsers, the top-level scope is the global scope.
// That means that in browsers if you're in the global scope var something will define a global variable.
// In Node this is different. The top-level scope is not the global scope; var something inside a Node module will be local to that module.
__filename; // The filename of the code being executed. (absolute path)
__dirname; // The name of the directory that the currently executing script resides in. (absolute path)
module; // A reference to the current module. In particular module.exports is used for defining what a module exports and makes available through require().
exports; // A reference to the module.exports that is shorter to type.
process; // The process object is a global object and can be accessed from anywhere. It is an instance of EventEmitter.
Buffer; // The Buffer class is a global type for dealing with binary data directly.
/* *******************************************************************************************
* CONSOLE
* http://nodejs.org/api/console.html
* ******************************************************************************************* */
console.log([data], [...]); // Prints to stdout with newline.
console.info([data], [...]); // Same as console.log.
console.error([data], [...]); // Same as console.log but prints to stderr.
console.warn([data], [...]); // Same as console.error.
console.dir(obj); // Uses util.inspect on obj and prints resulting string to stdout.
console.time(label); // Mark a time.
console.timeEnd(label); // Finish timer, record output.
console.trace(label); // Print a stack trace to stderr of the current position.
console.assert(expression, [message]); // Same as assert.ok() where if the expression evaluates as false throw an AssertionError with message.
/* *******************************************************************************************
* TIMERS
* http://nodejs.org/api/timers.html
* ******************************************************************************************* */
setTimeout(callback, delay, [arg], [...]); // To schedule execution of a one-time callback after delay milliseconds. Optionally you can also pass arguments to the callback.
clearTimeout(t); // Stop a timer that was previously created with setTimeout().
setInterval(callback, delay, [arg], [...]); // To schedule the repeated execution of callback every delay milliseconds. Optionally you can also pass arguments to the callback.
clearInterval(t); // Stop a timer that was previously created with setInterval().
setImmediate(callback, [arg], [...]); // To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval.
clearImmediate(immediateObject); // Stop a timer that was previously created with setImmediate().
unref(); // Allow you to create a timer that is active but if it is the only item left in the event loop, node won't keep the program running.
ref(); // If you had previously unref()d a timer you can call ref() to explicitly request the timer hold the program open.
/* *******************************************************************************************
* MODULES
* http://nodejs.org/api/modules.html
* ******************************************************************************************* */
var module = require('./module.js'); // Loads the module module.js in the same directory.
module.require('./another_module.js'); // load another_module as if require() was called from the module itself.
module.id; // The identifier for the module. Typically this is the fully resolved filename.
module.filename; // The fully resolved filename to the module.
module.loaded; // Whether or not the module is done loading, or is in the process of loading.
module.parent; // The module that required this one.
module.children; // The module objects required by this one.
exports.area = function (r) {
return Math.PI * r * r;
};
// If you want the root of your module's export to be a function (such as a constructor)
// or if you want to export a complete object in one assignment instead of building it one property at a time,
// assign it to module.exports instead of exports.
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}
/* *******************************************************************************************
* PROCESS
* http://nodejs.org/api/process.html
* ******************************************************************************************* */
process.on('exit', function(code) {}); // Emitted when the process is about to exit
process.on('uncaughtException', function(err) {}); // Emitted when an exception bubbles all the way back to the event loop. (should not be used)
process.stdout; // A writable stream to stdout.
process.stderr; // A writable stream to stderr.
process.stdin; // A readable stream for stdin.
process.argv; // An array containing the command line arguments.
process.env; // An object containing the user environment.
process.execPath; // This is the absolute pathname of the executable that started the process.
process.execArgv; // This is the set of node-specific command line options from the executable that started the process.
process.arch; // What processor architecture you're running on: 'arm', 'ia32', or 'x64'.
process.config; // An Object containing the JavaScript representation of the configure options that were used to compile the current node executable.
process.pid; // The PID of the process.
process.platform; // What platform you're running on: 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'.
process.title; // Getter/setter to set what is displayed in 'ps'.
process.version; // A compiled-in property that exposes NODE_VERSION.
process.versions; // A property exposing version strings of node and its dependencies.
process.abort(); // This causes node to emit an abort. This will cause node to exit and generate a core file.
process.chdir(dir); // Changes the current working directory of the process or throws an exception if that fails.
process.cwd(); // Returns the current working directory of the process.
process.exit([code]); // Ends the process with the specified code. If omitted, exit uses the 'success' code 0.
process.getgid(); // Gets the group identity of the process.
process.setgid(id); // Sets the group identity of the process.
process.getuid(); // Gets the user identity of the process.
process.setuid(id); // Sets the user identity of the process.
process.getgroups(); // Returns an array with the supplementary group IDs.
process.setgroups(grps); // Sets the supplementary group IDs.
process.initgroups(user, extra_grp); // Reads /etc/group and initializes the group access list, using all groups of which the user is a member.
process.kill(pid, [signal]); // Send a signal to a process. pid is the process id and signal is the string describing the signal to send.
process.memoryUsage(); // Returns an object describing the memory usage of the Node process measured in bytes.
process.nextTick(callback); // On the next loop around the event loop call this callback.
process.maxTickDepth; // Callbacks passed to process.nextTick will usually be called at the end of the current flow of execution, and are thus approximately as fast as calling a function synchronously.
process.umask([mask]); // Sets or reads the process's file mode creation mask.
process.uptime(); // Number of seconds Node has been running.
process.hrtime(); // Returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.
/* *******************************************************************************************
* CHILD PROCESS
* http://nodejs.org/api/child_process.html
* ******************************************************************************************* */
// Node provides a tri-directional popen facility through the child_process module.
// It is possible to stream data through a child's stdin, stdout, and stderr in a fully non-blocking way.
ChildProcess; // Class. ChildProcess is an EventEmitter.
child.stdin; // A Writable Stream that represents the child process's stdin
child.stdout; // A Readable Stream that represents the child process's stdout
child.stderr; // A Readable Stream that represents the child process's stderr.
child.pid; // The PID of the child process
child.connected; // If .connected is false, it is no longer possible to send messages
child.kill([signal]); // Send a signal to the child process
child.send(message, [sendHandle]); // When using child_process.fork() you can write to the child using child.send(message, [sendHandle]) and messages are received by a 'message' event on the child.
child.disconnect(); // Close the IPC channel between parent and child, allowing the child to exit gracefully once there are no other connections keeping it alive.
child_process.spawn(command, [args], [options]); // Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.
child_process.exec(command, [options], callback); // Runs a command in a shell and buffers the output.
child_process.execFile(file, [args], [options], [callback]); // Runs a command in a shell and buffers the output.
child_process.fork(modulePath, [args], [options]); // This is a special case of the spawn() functionality for spawning Node processes. In addition to having all the methods in a normal ChildProcess instance, the returned object has a communication channel built-in.
/* *******************************************************************************************
* UTIL
* http://nodejs.org/api/util.html
* ******************************************************************************************* */
// These functions are in the module 'util'. Use require('util') to access them.
util.format(format, [...]); // Returns a formatted string using the first argument as a printf-like format. (%s, %d, %j)
util.debug(string); // A synchronous output function. Will block the process and output string immediately to stderr.
util.error([...]); // Same as util.debug() except this will output all arguments immediately to stderr.
util.puts([...]); // A synchronous output function. Will block the process and output all arguments to stdout with newlines after each argument.
util.print([...]); // A synchronous output function. Will block the process, cast each argument to a string then output to stdout. (no newlines)
util.log(string); // Output with timestamp on stdout.
util.inspect(object, [opts]); // Return a string representation of object, which is useful for debugging. (options: showHidden, depth, colors, customInspect)
util.isArray(object); // Returns true if the given "object" is an Array. false otherwise.
util.isRegExp(object); // Returns true if the given "object" is a RegExp. false otherwise.
util.isDate(object); // Returns true if the given "object" is a Date. false otherwise.
util.isError(object); // Returns true if the given "object" is an Error. false otherwise.
util.promisify(fn) // Takes a function whose last argument is a callback and returns a version that returns promises.
util.inherits(constructor, superConstructor); // Inherit the prototype methods from one constructor into another.
/* *******************************************************************************************
* EVENTS
* http://nodejs.org/api/events.html
* ******************************************************************************************* */
// All objects which emit events are instances of events.EventEmitter. You can access this module by doing: require("events");
// To access the EventEmitter class, require('events').EventEmitter.
// All EventEmitters emit the event 'newListener' when new listeners are added and 'removeListener' when a listener is removed.
emitter.addListener(event, listener); // Adds a listener to the end of the listeners array for the specified event.
emitter.on(event, listener); // Same as emitter.addListener().
emitter.once(event, listener); // Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.
emitter.removeListener(event, listener); // Remove a listener from the listener array for the specified event.
emitter.removeAllListeners([event]); // Removes all listeners, or those of the specified event.
emitter.setMaxListeners(n); // By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.
emitter.listeners(event); // Returns an array of listeners for the specified event.
emitter.emit(event, [arg1], [arg2], [...]); // Execute each of the listeners in order with the supplied arguments. Returns true if event had listeners, false otherwise.
EventEmitter.listenerCount(emitter, event); // Return the number of listeners for a given event.
/* *******************************************************************************************
* STREAM
* http://nodejs.org/api/stream.html
* ******************************************************************************************* */
// A stream is an abstract interface implemented by various objects in Node. For example a request to an HTTP server is a stream, as is stdout.
// Streams are readable, writable, or both. All streams are instances of EventEmitter.
// The Readable stream interface is the abstraction for a source of data that you are reading from.
// In other words, data comes out of a Readable stream.
// A Readable stream will not start emitting data until you indicate that you are ready to receive it.
// Examples of readable streams include: http responses on the client, http requests on the server, fs read streams
// zlib streams, crypto streams, tcp sockets, child process stdout and stderr, process.stdin.
var readable = getReadableStreamSomehow();
readable.on('readable', function() {}); // When a chunk of data can be read from the stream, it will emit a 'readable' event.
readable.on('data', function(chunk) {}); // If you attach a data event listener, then it will switch the stream into flowing mode, and data will be passed to your handler as soon as it is available.
readable.on('end', function() {}); // This event fires when there will be no more data to read.
readable.on('close', function() {}); // Emitted when the underlying resource (for example, the backing file descriptor) has been closed. Not all streams will emit this.
readable.on('error', function() {}); // Emitted if there was an error receiving data.
// The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
// This method should only be called in non-flowing mode. In flowing-mode, this method is called automatically until the internal buffer is drained.
readable.read([size]);
readable.setEncoding(encoding); // Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
readable.resume(); // This method will cause the readable stream to resume emitting data events.
readable.pause(); // This method will cause a stream in flowing-mode to stop emitting data events.
readable.pipe(destination, [options]); // This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
readable.unpipe([destination]); // This method will remove the hooks set up for a previous pipe() call. If the destination is not specified, then all pipes are removed.
readable.unshift(chunk); // This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
// The Writable stream interface is an abstraction for a destination that you are writing data to.
// Examples of writable streams include: http requests on the client, http responses on the server, fs write streams,
// zlib streams, crypto streams, tcp sockets, child process stdin, process.stdout, process.stderr.
var writer = getWritableStreamSomehow();
writable.write(chunk, [encoding], [callback]); // This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled.
writer.once('drain', write); // If a writable.write(chunk) call returns false, then the drain event will indicate when it is appropriate to begin writing more data to the stream.
writable.end([chunk], [encoding], [callback]); // Call this method when no more data will be written to the stream.
writer.on('finish', function() {}); // When the end() method has been called, and all data has been flushed to the underlying system, this event is emitted.
writer.on('pipe', function(src) {}); // This is emitted whenever the pipe() method is called on a readable stream, adding this writable to its set of destinations.
writer.on('unpipe', function(src) {}); // This is emitted whenever the unpipe() method is called on a readable stream, removing this writable from its set of destinations.
writer.on('error', function(src) {}); // Emitted if there was an error when writing or piping data.
// Duplex streams are streams that implement both the Readable and Writable interfaces. See above for usage.
// Examples of Duplex streams include: tcp sockets, zlib streams, crypto streams.
// Transform streams are Duplex streams where the output is in some way computed from the input. They implement both the Readable and Writable interfaces. See above for usage.
// Examples of Transform streams include: zlib streams, crypto streams.
/* *******************************************************************************************
* FILE SYSTEM
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// To use this module do require('fs').
// All the methods have asynchronous and synchronous forms.
fs.rename(oldPath, newPath, callback); // Asynchronous rename. No arguments other than a possible exception are given to the completion callback.Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.renameSync(oldPath, newPath); // Synchronous rename.
fs.ftruncate(fd, len, callback); // Asynchronous ftruncate. No arguments other than a possible exception are given to the completion callback.
fs.ftruncateSync(fd, len); // Synchronous ftruncate.
fs.truncate(path, len, callback); // Asynchronous truncate. No arguments other than a possible exception are given to the completion callback.
fs.truncateSync(path, len); // Synchronous truncate.
fs.chown(path, uid, gid, callback); // Asynchronous chown. No arguments other than a possible exception are given to the completion callback.
fs.chownSync(path, uid, gid); // Synchronous chown.
fs.fchown(fd, uid, gid, callback); // Asynchronous fchown. No arguments other than a possible exception are given to the completion callback.
fs.fchownSync(fd, uid, gid); // Synchronous fchown.
fs.lchown(path, uid, gid, callback); // Asynchronous lchown. No arguments other than a possible exception are given to the completion callback.
fs.lchownSync(path, uid, gid); // Synchronous lchown.
fs.chmod(path, mode, callback); // Asynchronous chmod. No arguments other than a possible exception are given to the completion callback.
fs.chmodSync(path, mode); // Synchronous chmod.
fs.fchmod(fd, mode, callback); // Asynchronous fchmod. No arguments other than a possible exception are given to the completion callback.
fs.fchmodSync(fd, mode); // Synchronous fchmod.
fs.lchmod(path, mode, callback); // Asynchronous lchmod. No arguments other than a possible exception are given to the completion callback.
fs.lchmodSync(path, mode); // Synchronous lchmod.
fs.stat(path, callback); // Asynchronous stat. The callback gets two arguments (err, stats) where stats is a fs.Stats object.
fs.statSync(path); // Synchronous stat. Returns an instance of fs.Stats.
fs.lstat(path, callback); // Asynchronous lstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
fs.lstatSync(path); // Synchronous lstat. Returns an instance of fs.Stats.
fs.fstat(fd, callback); // Asynchronous fstat. The callback gets two arguments (err, stats) where stats is a fs.Stats object. fstat() is identical to stat(), except that the file to be stat-ed is specified by the file descriptor fd.
fs.fstatSync(fd); // Synchronous fstat. Returns an instance of fs.Stats.
fs.link(srcpath, dstpath, callback); // Asynchronous link. No arguments other than a possible exception are given to the completion callback.
fs.linkSync(srcpath, dstpath); // Synchronous link.
fs.symlink(srcpath, dstpath, [type], callback); // Asynchronous symlink. No arguments other than a possible exception are given to the completion callback. The type argument can be set to 'dir', 'file', or 'junction' (default is 'file') and is only available on Windows (ignored on other platforms)
fs.symlinkSync(srcpath, dstpath, [type]); // Synchronous symlink.
fs.readlink(path, callback); // Asynchronous readlink. The callback gets two arguments (err, linkString).
fs.readlinkSync(path); // Synchronous readlink. Returns the symbolic link's string value.
fs.unlink(path, callback); // Asynchronous unlink. No arguments other than a possible exception are given to the completion callback.
fs.unlinkSync(path); // Synchronous unlink.
fs.realpath(path, [cache], callback); // Asynchronous realpath. The callback gets two arguments (err, resolvedPath).
fs.realpathSync(path, [cache]); // Synchronous realpath. Returns the resolved path.
fs.rmdir(path, callback); // Asynchronous rmdir. No arguments other than a possible exception are given to the completion callback.
fs.rmdirSync(path); // Synchronous rmdir.
fs.mkdir(path, [mode], callback); // Asynchronous mkdir. No arguments other than a possible exception are given to the completion callback. mode defaults to 0777.
fs.mkdirSync(path, [mode]); // Synchronous mkdir.
fs.readdir(path, callback); // Asynchronous readdir. Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
fs.readdirSync(path); // Synchronous readdir. Returns an array of filenames excluding '.' and '..'.
fs.close(fd, callback); // Asynchronous close. No arguments other than a possible exception are given to the completion callback.
fs.closeSync(fd); // Synchronous close.
fs.open(path, flags, [mode], callback); // Asynchronous file open.
fs.openSync(path, flags, [mode]); // Synchronous version of fs.open().
fs.utimes(path, atime, mtime, callback); // Change file timestamps of the file referenced by the supplied path.
fs.utimesSync(path, atime, mtime); // Synchronous version of fs.utimes().
fs.futimes(fd, atime, mtime, callback); // Change the file timestamps of a file referenced by the supplied file descriptor.
fs.futimesSync(fd, atime, mtime); // Synchronous version of fs.futimes().
fs.fsync(fd, callback); // Asynchronous fsync. No arguments other than a possible exception are given to the completion callback.
fs.fsyncSync(fd); // Synchronous fsync.
fs.write(fd, buffer, offset, length, position, callback); // Write buffer to the file specified by fd.
fs.writeSync(fd, buffer, offset, length, position); // Synchronous version of fs.write(). Returns the number of bytes written.
fs.read(fd, buffer, offset, length, position, callback); // Read data from the file specified by fd.
fs.readSync(fd, buffer, offset, length, position); // Synchronous version of fs.read. Returns the number of bytesRead.
fs.readFile(filename, [options], callback); // Asynchronously reads the entire contents of a file.
fs.readFileSync(filename, [options]); // Synchronous version of fs.readFile. Returns the contents of the filename. If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
fs.writeFile(filename, data, [options], callback); // Asynchronously writes data to a file, replacing the file if it already exists. data can be a string or a buffer.
fs.writeFileSync(filename, data, [options]); // The synchronous version of fs.writeFile.
fs.appendFile(filename, data, [options], callback); // Asynchronously append data to a file, creating the file if it not yet exists. data can be a string or a buffer.
fs.appendFileSync(filename, data, [options]); // The synchronous version of fs.appendFile.
fs.watch(filename, [options], [listener]); // Watch for changes on filename, where filename is either a file or a directory. The returned object is a fs.FSWatcher. The listener callback gets two arguments (event, filename). event is either 'rename' or 'change', and filename is the name of the file which triggered the event.
fs.exists(path, callback); // Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false. (should not be used)
fs.existsSync(path); // Synchronous version of fs.exists. (should not be used)
// fs.Stats: objects returned from fs.stat(), fs.lstat() and fs.fstat() and their synchronous counterparts are of this type.
stats.isFile();
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink() // (only valid with fs.lstat())
stats.isFIFO()
stats.isSocket()
fs.createReadStream(path, [options]); // Returns a new ReadStream object.
fs.createWriteStream(path, [options]); // Returns a new WriteStream object.
/* *******************************************************************************************
* PATH
* http://nodejs.org/api/fs.html
* ******************************************************************************************* */
// Use require('path') to use this module.
// This module contains utilities for handling and transforming file paths.
// Almost all these methods perform only string transformations.
// The file system is not consulted to check whether paths are valid.
path.normalize(p); // Normalize a string path, taking care of '..' and '.' parts.
path.join([path1], [path2], [...]); // Join all arguments together and normalize the resulting path.
path.resolve([from ...], to); // Resolves 'to' to an absolute path.
path.relative(from, to); // Solve the relative path from 'from' to 'to'.
path.dirname(p); // Return the directory name of a path. Similar to the Unix dirname command.
path.basename(p, [ext]); // Return the last portion of a path. Similar to the Unix basename command.
path.extname(p); // Return the extension of the path, from the last '.' to end of string in the last portion of the path.
path.sep; // The platform-specific file separator. '\\' or '/'.
path.delimiter; // The platform-specific path delimiter, ';' or ':'.
/* *******************************************************************************************
* HTTP
* http://nodejs.org/api/http.html
* ******************************************************************************************* */
// To use the HTTP server and client one must require('http').
http.STATUS_CODES; // A collection of all the standard HTTP response status codes, and the short description of each.
http.request(options, [callback]); // This function allows one to transparently issue requests.
http.get(options, [callback]); // Set the method to GET and calls req.end() automatically.
server = http.createServer([requestListener]); // Returns a new web server object. The requestListener is a function which is automatically added to the 'request' event.
server.listen(port, [hostname], [backlog], [callback]); // Begin accepting connections on the specified port and hostname.
server.listen(path, [callback]); // Start a UNIX socket server listening for connections on the given path.
server.listen(handle, [callback]); // The handle object can be set to either a server or socket (anything with an underlying _handle member), or a {fd: <n>} object.
server.close([callback]); // Stops the server from accepting new connections.
server.setTimeout(msecs, callback); // Sets the timeout value for sockets, and emits a 'timeout' event on the Server object, passing the socket as an argument, if a timeout occurs.
server.maxHeadersCount; // Limits maximum incoming headers count, equal to 1000 by default. If set to 0 - no limit will be applied.
server.timeout; // The number of milliseconds of inactivity before a socket is presumed to have timed out.
server.on('request', function (request, response) { }); // Emitted each time there is a request.
server.on('connection', function (socket) { }); // When a new TCP stream is established.
server.on('close', function () { }); // Emitted when the server closes.
server.on('checkContinue', function (request, response) { }); // Emitted each time a request with an http Expect: 100-continue is received.
server.on('connect', function (request, socket, head) { }); // Emitted each time a client requests a http CONNECT method.
server.on('upgrade', function (request, socket, head) { }); // Emitted each time a client requests a http upgrade.
server.on('clientError', function (exception, socket) { }); // If a client connection emits an 'error' event - it will forwarded here.
request.write(chunk, [encoding]); // Sends a chunk of the body.
request.end([data], [encoding]); // Finishes sending the request. If any parts of the body are unsent, it will flush them to the stream.
request.abort(); // Aborts a request.
request.setTimeout(timeout, [callback]); // Once a socket is assigned to this request and is connected socket.setTimeout() will be called.
request.setNoDelay([noDelay]); // Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.
request.setSocketKeepAlive([enable], [initialDelay]); // Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.
request.on('response', function(response) { }); // Emitted when a response is received to this request. This event is emitted only once.
request.on('socket', function(socket) { }); // Emitted after a socket is assigned to this request.
request.on('connect', function(response, socket, head) { }); // Emitted each time a server responds to a request with a CONNECT method. If this event isn't being listened for, clients receiving a CONNECT method will have their connections closed.
request.on('upgrade', function(response, socket, head) { }); // Emitted each time a server responds to a request with an upgrade. If this event isn't being listened for, clients receiving an upgrade header will have their connections closed.
request.on('continue', function() { }); // Emitted when the server sends a '100 Continue' HTTP response, usually because the request contained 'Expect: 100-continue'. This is an instruction that the client should send the request body.
response.write(chunk, [encoding]); // This sends a chunk of the response body. If this merthod is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
response.writeContinue(); // Sends a HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent.
response.writeHead(statusCode, [reasonPhrase], [headers]); // Sends a response header to the request.
response.setTimeout(msecs, callback); // Sets the Socket's timeout value to msecs. If a callback is provided, then it is added as a listener on the 'timeout' event on the response object.
response.setHeader(name, value); // Sets a single header value for implicit headers. If this header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings here if you need to send multiple headers with the same name.
response.getHeader(name); // Reads out a header that's already been queued but not sent to the client. Note that the name is case insensitive.
response.removeHeader(name); // Removes a header that's queued for implicit sending.
response.addTrailers(headers); // This method adds HTTP trailing headers (a header but at the end of the message) to the response.
response.end([data], [encoding]); // This method signals to the server that all of the response headers and body have been sent; that server should consider this message complete. The method, response.end(), MUST be called on each response.
response.statusCode; // When using implicit headers (not calling response.writeHead() explicitly), this property controls the status code that will be sent to the client when the headers get flushed.
response.headersSent; // Boolean (read-only). True if headers were sent, false otherwise.
response.sendDate; // When true, the Date header will be automatically generated and sent in the response if it is not already present in the headers. Defaults to true.
response.on('close', function () { }); // Indicates that the underlying connection was terminated before response.end() was called or able to flush.
response.on('finish', function() { }); // Emitted when the response has been sent.
message.httpVersion; // In case of server request, the HTTP version sent by the client. In the case of client response, the HTTP version of the connected-to server.
message.headers; // The request/response headers object.
message.trailers; // The request/response trailers object. Only populated after the 'end' event.
message.method; // The request method as a string. Read only. Example: 'GET', 'DELETE'.
message.url; // Request URL string. This contains only the URL that is present in the actual HTTP request.
message.statusCode; // The 3-digit HTTP response status code. E.G. 404.
message.socket; // The net.Socket object associated with the connection.
message.setTimeout(msecs, callback); // Calls message.connection.setTimeout(msecs, callback).
/* *******************************************************************************************
* URL
* http://nodejs.org/api/url.html
* ******************************************************************************************* */
// This module has utilities for URL resolution and parsing. Call require('url') to use it.
url.parse(urlStr, [parseQueryString], [slashesDenoteHost]); // Take a URL string, and return an object.
url.format(urlObj); // Take a parsed URL object, and return a formatted URL string.
url.resolve(from, to); // Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.
/* *******************************************************************************************
* QUERY STRING
* http://nodejs.org/api/querystring.html
* ******************************************************************************************* */
// This module provides utilities for dealing with query strings. Call require('querystring') to use it.
querystring.stringify(obj, [sep], [eq]); // Serialize an object to a query string. Optionally override the default separator ('&') and assignment ('=') characters.
querystring.parse(str, [sep], [eq], [options]); // Deserialize a query string to an object. Optionally override the default separator ('&') and assignment ('=') characters.
/* *******************************************************************************************
* ASSERT
* http://nodejs.org/api/assert.html
* ******************************************************************************************* */
// This module is used for writing unit tests for your applications, you can access it with require('assert').
assert.fail(actual, expected, message, operator); // Throws an exception that displays the values for actual and expected separated by the provided operator.
assert(value, message); assert.ok(value, [message]); // Tests if value is truthy, it is equivalent to assert.equal(true, !!value, message);
assert.equal(actual, expected, [message]); // Tests shallow, coercive equality with the equal comparison operator ( == ).
assert.notEqual(actual, expected, [message]); // Tests shallow, coercive non-equality with the not equal comparison operator ( != ).
assert.deepEqual(actual, expected, [message]); // Tests for deep equality.
assert.notDeepEqual(actual, expected, [message]); // Tests for any deep inequality.
assert.strictEqual(actual, expected, [message]); // Tests strict equality, as determined by the strict equality operator ( === )
assert.notStrictEqual(actual, expected, [message]); // Tests strict non-equality, as determined by the strict not equal operator ( !== )
assert.throws(block, [error], [message]); // Expects block to throw an error. error can be constructor, RegExp or validation function.
assert.doesNotThrow(block, [message]); // Expects block not to throw an error, see assert.throws for details.
assert.ifError(value); // Tests if value is not a false value, throws if it is a true value. Useful when testing the first argument, error in callbacks.
/* *******************************************************************************************
* OS
* http://nodejs.org/api/os.html
* ******************************************************************************************* */
// Provides a few basic operating-system related utility functions.
// Use require('os') to access this module.
os.tmpdir(); // Returns the operating system's default directory for temp files.
os.endianness(); // Returns the endianness of the CPU. Possible values are "BE" or "LE".
os.hostname(); // Returns the hostname of the operating system.
os.type(); // Returns the operating system name.
os.platform(); // Returns the operating system platform.
os.arch(); // Returns the operating system CPU architecture.
os.release(); // Returns the operating system release.
os.uptime(); // Returns the system uptime in seconds.
os.loadavg(); // Returns an array containing the 1, 5, and 15 minute load averages.
os.totalmem(); // Returns the total amount of system memory in bytes.
os.freemem(); // Returns the amount of free system memory in bytes.
os.cpus(); // Returns an array of objects containing information about each CPU/core installed: model, speed (in MHz), and times (an object containing the number of milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).
os.networkInterfaces(); // Get a list of network interfaces.
os.EOL; // A constant defining the appropriate End-of-line marker for the operating system.
/* *******************************************************************************************
* BUFFER
* http://nodejs.org/api/buffer.html
* ******************************************************************************************* */
// Buffer is used to dealing with binary data
// Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap
Buffer.from(size); // Allocates a new buffer of size octets.
Buffer.from(array); // Allocates a new buffer using an array of octets.
Buffer.from(str, [encoding]); // Allocates a new buffer containing the given str. encoding defaults to 'utf8'.
Buffer.isEncoding(encoding); // Returns true if the encoding is a valid encoding argument, or false otherwise.
Buffer.isBuffer(obj); // Tests if obj is a Buffer
Buffer.concat(list, [totalLength]); // Returns a buffer which is the result of concatenating all the buffers in the list together.
Buffer.byteLength(string, [encoding]); // Gives the actual byte length of a string.
buf.write(string, [offset], [length], [encoding]); // Writes string to the buffer at offset using the given encoding
buf.toString([encoding], [start], [end]); // Decodes and returns a string from buffer data encoded with encoding (defaults to 'utf8') beginning at start (defaults to 0) and ending at end (defaults to buffer.length).
buf.toJSON(); // Returns a JSON-representation of the Buffer instance, which is identical to the output for JSON Arrays
buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd]); // Does copy between buffers. The source and target regions can be overlapped
buf.slice([start], [end]); // Returns a new buffer which references the same memory as the old, but offset and cropped by the start (defaults to 0) and end (defaults to buffer.length) indexes. Negative indexes start from the end of the buffer.
buf.fill(value, [offset], [end]); // Fills the buffer with the specified value
buf[index]; // Get and set the octet at index
buf.length; // The size of the buffer in bytes, Note that this is not necessarily the size of the contents
buffer.INSPECT_MAX_BYTES; // How many bytes will be returned when buffer.inspect() is called. This can be overridden by user modules.

React

Components

import React from 'react'
import ReactDOM from 'react-dom'
class Hello extends React.Component {
  render () {
    return <div className='message-box'>
      Hello {this.props.name}
    </div>
  }
}
const el = document.body
ReactDOM.render(<Hello name='John' />, el)

Use the React.js jsfiddle to start hacking. (or the unofficial jsbin)

Import multiple exports

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
class Hello extends Component {
  ...
}

Properties

<Video fullscreen={true} autoplay={false} />
render () {
  this.props.fullscreen
  const { fullscreen, autoplay } = this.props
  ···
}

Use this.props to access properties passed to the component.

See: Properties

States

constructor(props) {
  super(props)
  this.state = { username: undefined }
}
this.setState({ username: 'rstacruz' })
render () {
  this.state.username
  const { username } = this.state
  ···
}

Use states (this.state) to manage dynamic data.

With Babel you can use proposal-class-fields and get rid of constructor

class Hello extends Component {
  state = { username: undefined };
  ...
}

See: States

Nesting

class Info extends Component {
  render () {
    const { avatar, username } = this.props

    return <div>
      <UserAvatar src={avatar} />
      <UserProfile username={username} />
    </div>
  }
}

As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.

import React, {
  Component,
  Fragment
} from 'react'

class Info extends Component {
  render () {
    const { avatar, username } = this.props

    return (
      <Fragment>
        <UserAvatar src={avatar} />
        <UserProfile username={username} />
      </Fragment>
    )
  }
}

Nest components to separate concerns.

See: Composing Components

Children

<AlertBox>
  <h1>You have pending notifications</h1>
</AlertBox>
class AlertBox extends Component {
  render () {
    return <div className='alert-box'>
      {this.props.children}
    </div>
  }
}

Children are passed as the children property.

Defaults

Setting default props

Hello.defaultProps = {
  color: 'blue'
}

See: defaultProps

Setting default state

class Hello extends Component {
  constructor (props) {
    super(props)
    this.state = { visible: true }
  }
}

Set the default state in the constructor().

And without constructor using Babel with proposal-class-fields.

class Hello extends Component {
    state = { visible: true }
  }
}

See: Setting the default state

Other components

Functional components

function MyComponent ({ name }) {
  return <div className='message-box'>
    Hello {name}
  </div>
}

Functional components have no state. Also, their props are passed as the first parameter to a function.

See: Function and Class Components

Pure components

import React, {PureComponent} from 'react'

class MessageBox extends PureComponent {
  ···
}

Performance-optimized version of React.Component. Doesn't rerender if props/state hasn't changed.

See: Pure components

Component API

this.forceUpdate()
this.setState({ ... })
this.setState(state => { ... })
this.state
this.props

These methods and properties are available for Component instances.

See: Component API

Lifecycle

Mounting

Method Description
constructor (props) Before rendering #
componentWillMount() Don't use this #
render() Render #
componentDidMount() After rendering (DOM available) #
--- ---
componentWillUnmount() Before DOM removal #
--- ---
componentDidCatch() Catch errors (16+) #

Set initial the state on constructor(). Add DOM event handlers, timers (etc) on componentDidMount(), then remove them on componentWillUnmount().

Updating

Method Description
componentDidUpdate (prevProps, prevState, snapshot) Use setState() here, but remember to compare props
shouldComponentUpdate (newProps, newState) Skips render() if returns false
render() Render
componentDidUpdate (prevProps, prevState) Operate on the DOM here

Called when parents change properties and .setState(). These are not called for initial renders.

See: Component specs

Hooks (New)

State Hook

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Hooks are a new addition in React 16.8.

See: Hooks at a Glance

Declaring multiple state variables

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

Effect hook

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.

By default, React runs the effects after every render — including the first render.

Building your own hooks

Define FriendStatus

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  }, [props.friend.id]);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

Effects may also optionally specify how to “clean up” after them by returning a function.

Use FriendStatus

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

See: Building Your Own Hooks

Hooks API Reference

Also see: Hooks FAQ

Basic Hooks

Hook Description
useState(initialState)
useEffect(() => { ... })
useContext(MyContext) value returned from React.createContext

Full details: Basic Hooks

Additional Hooks

Hook Description
useReducer(reducer, initialArg, init)
useCallback(() => { ... })
useMemo(() => { ... })
useRef(initialValue)
useImperativeHandle(ref, () => { ... })
useLayoutEffect identical to useEffect, but it fires synchronously after all DOM mutations
useDebugValue(value) display a label for custom hooks in React DevTools

Full details: Additional Hooks

DOM nodes

References

class MyComponent extends Component {
  render () {
    return <div>
      <input ref={el => this.input = el} />
    </div>
  }

  componentDidMount () {
    this.input.focus()
  }
}

Allows access to DOM nodes.

See: Refs and the DOM

DOM Events

class MyComponent extends Component {
  render () {
    <input type="text"
        value={this.state.value}
        onChange={event => this.onChange(event)} />
  }

  onChange (event) {
    this.setState({ value: event.target.value })
  }
}

Pass functions to attributes like onChange.

See: Events

Other features

Transferring props

<VideoPlayer src="video.mp4" />
class VideoPlayer extends Component {
  render () {
    return <VideoEmbed {...this.props} />
  }
}

Propagates src="..." down to the sub-component.

See Transferring props

Top-level API

React.createClass({ ... })
React.isValidElement(c)
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)

There are more, but these are most common.

See: React top-level API

JSX patterns

Style shorthand

const style = { height: 10 }
return <div style={style}></div>
return <div style={{ margin: 0, padding: 0 }}></div>

See: Inline styles

Inner HTML

function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />

See: Dangerously set innerHTML

Lists

class TodoList extends Component {
  render () {
    const { items } = this.props

    return <ul>
      {items.map(item =>
        <TodoItem item={item} key={item.key} />)}
    </ul>
  }
}

Always supply a key property.

Conditionals

<Fragment>
  {showMyComponent
    ? <MyComponent />
    : <OtherComponent />}
</Fragment>

Short-circuit evaluation

<Fragment>
  {showPopup && <Popup />}
  ...
</Fragment>

New features

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

render () {
  // Don't forget the keys!
  return [
    <li key="A">First item</li>,
    <li key="B">Second item</li>
  ]
}

Fragments

render () {
  // Fragments don't require keys!
  return (
    <Fragment>
      <li>First item</li>
      <li>Second item</li>
    </Fragment>
  )
}

See: Fragments and strings

Returning strings

render() {
  return 'Look ma, no spans!';
}

You can return just a string.

See: Fragments and strings

Errors

class MyComponent extends Component {
  ···
  componentDidCatch (error, info) {
    this.setState({ error })
  }
}

Catch errors via componentDidCatch. (React 16+)

See: Error handling in React 16

Portals

render () {
  return React.createPortal(
    this.props.children,
    document.getElementById('menu')
  )
}

This renders this.props.children into any location in the DOM.

See: Portals

Hydration

const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)

Use ReactDOM.hydrate instead of using ReactDOM.render if you're rendering over the output of ReactDOMServer.

See: Hydrate

Property validation

PropTypes

import PropTypes from 'prop-types'

See: Typechecking with PropTypes

| any | Anything |

Basic

| string | | | number | | | func | Function | | bool | True or false |

Enum

| oneOf(any) | Enum types | | oneOfType(type array) | Union |

Array

| array | | | arrayOf(...) | |

Object

| object | | | objectOf(...) | Object with values of a certain type | | instanceOf(...) | Instance of a class | | shape(...) | |

Elements

| element | React element | | node | DOM node |

Required

| (···).isRequired | Required |

Basic types

MyComponent.propTypes = {
  email:      PropTypes.string,
  seats:      PropTypes.number,
  callback:   PropTypes.func,
  isClosed:   PropTypes.bool,
  any:        PropTypes.any
}

Required types

MyCo.propTypes = {
  name:  PropTypes.string.isRequired
}

Elements

MyCo.propTypes = {
  // React element
  element: PropTypes.element,

  // num, string, element, or an array of those
  node: PropTypes.node
}

Enumerables (oneOf)

MyCo.propTypes = {
  direction: PropTypes.oneOf([
    'left', 'right'
  ])
}

Arrays and objects

MyCo.propTypes = {
  list: PropTypes.array,
  ages: PropTypes.arrayOf(PropTypes.number),
  user: PropTypes.object,
  user: PropTypes.objectOf(PropTypes.number),
  message: PropTypes.instanceOf(Message)
}
MyCo.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string,
    age:  PropTypes.number
  })
}

Use .array[Of], .object[Of], .instanceOf, .shape.

Custom validation

MyCo.propTypes = {
  customProp: (props, key, componentName) => {
    if (!/matchme/.test(props[key])) {
      return new Error('Validation failed!')
    }
  }
}

Also see

TypeScript

Basic types

any
void

boolean
number
string

null
undefined

string[]          /* or Array<string> */
[string, number]  /* tuple */

string | null | undefined   /* union */

never  /* unreachable */
enum Color {Red, Green, Blue = 4}
let c: Color = Color.Green

Declarations

let isDone: boolean
let isDone: boolean = false
function add (a: number, b: number): number {
  return a + b
}

// Return type is optional
function add (a: number, b: number) { ... }

Type assertions

Variables

let len: number = (input as string).length
let len: number = (<string> input).length  /* not allowed in JSX */

Functions

function object(this: {a: number, b: number}, a: number, b: number) {
  this.a = a;
  this.b = b;
  return this;
}

// this is used only for type declaration
let a = object(1,2);
// a has type {a: number, b: number}

Interfaces

Inline

function printLabel (options: { label: string }) {
  console.log(options.label)
}

// Note the semicolon
function getUser (): { name: string; age?: number } {
}

Explicit

interface LabelOptions {
  label: string
}

function printLabel(options: LabelOptions) { ... }

Optional properties

interface User {
  name: string,
  age?: number
}

Read only

interface User {
  readonly name: string
}

Dynamic keys

{
  [key: string]: Object[]
}

Type aliases

type Name = string | string[]

Function types

interface User { ... }

function getUser(callback: (user: User) => any) { callback({...}) }

getUser(function (user: User) { ... })

Classes

class Point {
  x: number
  y: number
  static instances = 0
  constructor(x: number, y: number) {
    this.x = x
    this.y = y
  }
}

Inheritance

class Point {...}

class Point3D extends Point {...}

interface Colored {...}

class Pixel extends Point implements Colored {...}

Short fields initialisation

class Point {
  static instances = 0;
  constructor(
    public x: number,
    public y: number,
  ){}
}

Fields which do not require initialisation

class Point {
  public someUselessValue!: number;
  ...
}

Generics

class Greeter<T> {
  greeting: T
  constructor(message: T) {
    this.greeting = message
  }
}

let greeter = new Greeter<string>('Hello, world')

Modules

export interface User { ... }

Type extraction

interface Building {
  room: {
    door: string,
    walls: string[],
  };
}

type Walls = Building['room']['walls']; // string[]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment