Commit f70487d0 authored by Nathan Bean's avatar Nathan Bean
Browse files

Added web foundations chapter

parent 585651cb
[submodule "themes/ksucs-hugo-theme"]
path = themes/ksucs-hugo-theme
url = git@github.com:russfeld/ksucs-hugo-theme.git
url = https://github.com/russfeld/ksucs-hugo-theme.git
baseURL = "https://ksucs-hugo.russfeld.me"
baseURL = "https://cs.ksu.edu/~nhbean/cis526"
languageCode = "en-us"
title = "K-State CS Hugo Framework"
title = "K-State CIS 526 Textbook"
# Change the default theme to be use when building the site with Hugo
theme = "ksucs-hugo-theme"
......@@ -12,9 +12,9 @@ page = [ "HTML", "Iframeable", "Teleprompter"]
section = [ "HTML", "Iframeable", "Teleprompter"]
[params]
editURL = "https://gitlab.cs.ksu.edu/russfeld/ksucs-hugo/tree/master/content/"
editURL = "https://gitlab.cs.ksu.edu/nhbean/cis526-textbook/tree/master/content/"
description = "K-State CS Hugo Framework"
author = "Russell Feldhausen"
author = "Nathan H. Bean"
showVisitedLinks = false
themeVariant = "purple"
disableLanguageSwitchingButton = true
......
---
title: "Course Introduction"
pre: "1."
weight: 10
date: 2018-08-24T10:53:26-05:00
---
// TODO: Embed Welcome Video
#### Resources
* Syllabus
#### Welcome Message
// TODO: Welcome Message
\ No newline at end of file
---
title: "Navigating Canvas"
pre: "2."
weight: 20
date: 2018-08-24T10:53:26-05:00
---
This course makes extensive use of several features of Canvas which you may or may not have worked with before. To give you the best experience in this course, this video will briefly describe those features and the best way to access them.
When you first access the course on Canvas, you will be shown this homepage, with my contact information and any important information about the course. This is a quick, easy reference for you if you ever need to get in touch with me.
Let’s walk through the options in the main menu to the left. First, any course announcements will be posted in the Announcements section, which is available here. Those announcements will also be configured to send emails to all students when they are posted, though in your personal Canvas settings you can disable email notifications if you so choose. Please make sure you check here often for any updates to course information.
The next section is Modules, which is where you’ll primarily interact with the course. You’ll notice that I’ve disabled several of the common menu items in this course, such as Files and Assignments. This is to simplify things for you as students, so you remember that all the course content is available in one place.
When you first arrive at the Modules section, you’ll see all of the content in the course laid out in order. If you like, you can minimize the modules you aren’t working on by clicking the arrow to the left of the module name.
As you look at each module, you’ll see that it gives quite a bit of information about the course. At the top of each module is an item telling you what parts of the module you must complete to continue. In this case, it says “Complete All Items.” Likewise, the following modules may list a prerequisite module, which you must complete before you can access it.
Within each module is a set of items, which must be completed in listed order. Under each item you’ll see information about what you must do in order to complete that item. For many of them, it will simply say “view,” which means you must view the item at least once to continue. Others may say “contribute,” “submit,” or give a minimum score required to continue. For assignments, it also helpfully gives the number of points available, and the due date.
Let’s click on the first item, Course Introduction, to get started. You’ve already been to this page by this point. Most course pages will consist of an embedded video, followed by links to any resources used or referenced in the video, including the slides and a downloadable version of the video. Finally, a rough video script will be posted on the page for your quick reference.
While I cannot force you to watch each video in its entirety, I highly recommend doing so. The script on the page may not accurately reflect all of the content in the video, nor can it show how to perform some tasks which are purely visual.
When you are ready to move to the next step in a module, click the “Next” button at the bottom of the page. Canvas will automatically add “Next” and “Previous” buttons to each piece of content which is accessed through the Modules section, which makes it very easy to work through the course content. I’ll click through a couple of items here.
At any point, you may click on the Modules link in the menu to the left to return to the Modules section of the site. You’ll notice that I’ve viewed the first few items in the first module, so I can access more items here. This is handy if you want to go back and review the content you’ve already seen, or if you leave and want to resume where you left off. Canvas will put green checkmarks to the right of items you’ve completed.
Continuing down the menu to the left, you’ll find links to the Piazza discussion forums for this course. If you have any questions about an assignment or would like to discuss any topic with your fellow classmates, this is a great place to do so. We’ll talk more about Piazza in just a second.
Finally, you’ll find the usual Canvas links to view your grades in the course, as well as a list of fellow students taking the course.
\ No newline at end of file
---
title: "Where to Find Help"
pre: "3."
weight: 30
date: 2018-08-24T10:53:26-05:00
---
#### Resources
* [K-State IT Help Desk](https://www.k-state.edu/its/helpdesk/) - [Email helpdesk@ksu.edu](helpdesk@ksu.edu)
* [Course Discussion Forums]
\ No newline at end of file
---
title: "What You'll Learn"
pre: "4."
weight: 40
date: 2018-08-24T10:53:26-05:00
---
Week 1: Web Application Fundamentals
* Module: Exploring the Document Object Model<br>
_The Document Object Model is a data structure used by the browser to compose and display the webpage from the HTML and CSS. It can be manipulated by JavaScript running on hte page._
* Readings 1.1-1.4
* [Tutorial] Creating a Dialog
* Module: Responsive Design
* Readings chapter 1.5-1.6
* [Tutorial] Responsive Card Layout
---
title: "Syllabus"
pre: "5."
weight: 50
date: 2018-08-24T10:53:26-05:00
---
## CIS 526 - Web App Development
### Instructor Contact Information
* **Instructor:** Nathan Bean (nhbean AT ksu DOT edu)
* **Office:** DUE 2216
* **Phone:** (785)483-9264 (Call/Text)
* **Website:** [https://nathanhbean.com](https://nathanhbean.com)
* **Virtual Office Hours:** By appointment via [Zoom](ksu.zoom.us). Schedule a meeting via email or RocketChat
### Preferred Methods of Communication:
* **Chat:** Quick questions via Rocket Chat are the preferred means of communication.   Questions whose answers may benefit the class I would encourage you to post in the #cis526 channel, as this keeps a public history your classmates can review.  More personal questions should be direct messaged to @nhbean.
* **Email:** For questions outside of this course, email to nhbean@ksu.edu is preferred.Phone/Text: Emergencies only! I will do my best to respond as quickly as possible.
* **Phone/Text:** _Emergencies only!_ I will do my best to respond as quickly as I can.
### Prerequisites
* CIS 501
* CMST 135 or equivalent experience in HTML, CSS, and JavaScript.
_Students may enroll in CIS courses only if they have earned a grade of C or better for each prerequisite to these courses._
### Course Structure
\ No newline at end of file
+++
title = "Chapter 0 Title"
title = "Introduction"
date = 2018-08-24T10:53:05-05:00
weight = 5
chapter = true
......@@ -8,6 +8,6 @@ pre = "<b>0. </b>"
### Chapter 0
# Chapter Title Here
# INTRODUCTION
Chapter 0 tagline.
Course Introductory Material for CIS 526 Online
---
title: "Introduction"
pre: "1. "
weight: 10
date: 2018-08-24T10:53:26-05:00
---
At this point, you should be familiar with the big three technologies of the world-wide-web _HTML_, _CSS_, and _JavaScript_ (Feel free to visit the appendices for a quick review). These three technologies work together to create the web pages you interact with every day. Each has a role to play in defining the final appearance of a web page:
* Hyper-Text Markup Language (HTML) provides the struture and content
* Cascading Style Sheets (CSS) determine how that content should appear visually
* JavaScript provides interactivity, allowing both the structure and appearance of the page to change dynamically
We often refer to this division of responsiblity as the _separation of concerns_. By placing all responsibility for appearance on a CSS file, we can refresh the look of a web application simply by replacing the old CSS file with a new one. Similarly, we can create a new page in our site that looks and feels like the rest of the site by creating a new HTML page that links to the site's existing CSS files.
While you have written HTML, CSS, and JavaScript files in your prior learning experiences, you might not have thought about just how these files are processed, and those styling rules applied. In this chapter we will explore this topic in detail, while introducing some more advanced uses for each.
\ No newline at end of file
---
title: "Document Object Model"
pre: "2. "
weight: 20
date: 2018-08-24T10:53:26-05:00
---
The Document Object Model (or DOM) is a data structure representing the content of a web page, created by the browser as it parses the website. The browser then makes this data structure accessible to scripts running on the page. The DOM is essentially a tree composed of objects representing the HTML elements and text on the page.
Consider this HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>Hello DOM!</title>
<link href="site.css"/>
</head>
<body>
<div class="banner">
<h1>Hello DOM!</h1>
<p>
The Document Object Model (DOM) is a programming API for HTML and XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. In the DOM specification, the term "document" is used in the broad sense - increasingly, XML is being used as a way of representing many different kinds of information that may be stored in diverse systems, and much of this would traditionally be seen as data rather than as documents. Nevertheless, XML presents this data as documents, and the DOM may be used to manage this data.
</p>
<a href="https://www.w3.org/TR/WD-DOM/introduction.html">From w3.org's What is the Document Object Model?</a>
</div>
</body>
<html>
```
When it is parsed by the browser, it is transformed into this tree:
![The DOM for the supplied HTML]({{<static "images/1.2.1.png">}})
### The DOM Tree and Developer Tools
Most browsers also expose the DOM tree through their developer tools. Try opening the example page in Chrome or your favorite browser using <a href='{{<static "examples/1.2.1/index.html">}}' target='_blank'>this link</a>.
Now open the developer tools for your browser:
* **Chrome** `CTRL + SHIFT + i` or right-click and select 'Inspect' from the context menu.
* **Edge** `CTRL + SHIFT + i` or right-click and select 'Inspect element' from the context menu.
* **Firefox** `CTRL + SHIFT + i` or right-click and select 'Inspect Element' from the context menu.
* **Safari** Developer tools must be enabled. See the [Safari User Guide](https://support.apple.com/guide/safari/use-the-developer-tools-in-the-develop-menu-sfri20948/mac)
You should see a new panel open in your browser, and under its 'elements' tab the DOM tree is displayed:
![The Elements tab of the Chrome Developer Tools]({{<static "images/1.2.2.png" >}})
Collapsed nodes can be expanded by clicking on the arrow next to them.
Try moving your mouse around the nodes in the DOM tree, and you'll see the corresponding element highlighted in the page. You can also _dynamically edit_ the DOM tree from the elements tab by right-clicking on a node.
Try right-clicking on the `<h1>` node and selecting 'edit text'. Change the text to "Hello Browser DOM". See how it changes the page?
The page is rendered from the DOM, so editing the DOM changes how the page appears. However, the initial structure of the DOM is dervied from the loaded HTML. This means if we refresh the page, any changes we made to the DOM using the developer tools will be lost, and the page will return to its original state. Give it a try - hit the refresh button.
{{% notice note %}}
For convenience, this textbook will use the [Chrome browser](https://www.google.com/chrome) for all developer tool reference images and discussions, but the other browsers offer much of the same functionality. If you prefer to use a different browser's web tools, look up the details in that browser's documentation.
{{% /notice %}}
You've now seen how the browser creates the DOM tree by parsing the HTML document and that DOM tree is used to render the page. Next, we'll look at how styles interact with the DOM to modify how it is displayed.
---
title: "CSS and the DOM"
pre: "3. "
weight: 30
date: 2018-08-24T10:53:26-05:00
---
Cascading style sheets (CSS) also interact with the DOM. Consider this CSS code:
```css
.banner {
border: 4px solid gold;
border-radius: 5rem;
background-color: goldenrod;
padding: 5rem;
color: brown;
}
.banner > h1 {
font-style: italic;
}
.banner p {
text-decoration: line-through;
font-size: 1.2rem;
}
```
When it is placed in the _site.css_ file referenced by the HTML we discussed in the last section, the rules it defines are evaluated in terms of the DOM tree. The result is the page now looks like this:
![The styled example page]({{<static "images/1.3.1.png">}})
Now let's talk about how this CSS code and the DOM interact.
Consider the selector `.banner`. It looks for any element whose class attribute includes the string `"banner"`. Hence, it matches the `<div>` element, adding a color, background color, border, and padding. This visualization of the DOM tree indicates the selected node in yellow:
![DOM tree visualization with marked .banner node]({{<static "images/1.3.2.png">}})
Notice how the text in both the `<h1>` element and the `<p>` element are a reddish color? That color is the one defined in the `.banner` rule: `color: #754907`. The rule applies not only to the selected node, but to _all its descendants in the DOM tree_. This is the 'cascading' part of cascading style sheets - the rules flow down the DOM tree until they are overridden by more specific css rules in descendant nodes.
The second way CSS interacts with the DOM tree is through the CSS selectors themselves.
For example, the selector `.banner > h1` uses the [child combinator](https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator) - the `>` symbol between `.banner` and `h1`. This indicates that the rule will be applied to any `<h1>` nodes that are _direct children_ of the node with the class of `"banner"`. As we can see from the DOM tree, the sole `<h1>` tag is a child of the `<div.banner>` node, so this rule is applied to it:
![DOM tree visualization with marked .banner > h1 node]({{<static "images/1.3.3.png">}})
Similarly, the `.banner p` tag uses the [descendant combinator](https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Selectors/Combinators) - the space between the `.banner` and `p`. This indicates that the rule will be applied to any `<p>` nodes that are _descended from_ the node with the class of `"banner"`. This will apply no matter how far down the tree those nodes appear. Thus, if we added more `<p>` elements inside of a `<div>` that was a child of the `<div.banner>` node, it would apply to them as well.
![DOM tree visualization with marked .banner p nodes]({{<static "images/1.3.4.png">}})
You can see the example with the styling applied by following <a href='{{<static "images/1.3.2.png">}}' target='_blank'>this link</a>. Try adding the div and two paragraphs with the developer tools. See how the styles are automatically applied to the new nodes in the DOM tree?
### CSS and Developer Tools
Speaking of developer tools, there is another handy tab that deals with CSS, the 'Styles' tab. It displays _all_ the css rules applied to a specific node. Select one of your new `<p>` elements. Notice how the styles tab shows the css rule `.banner p` that we've been discussing? Moreover, it tells you which CSS file and which line in that file the rule is found on.
![Styles tab in developer tools]({{<static "images/1.3.5.png">}})
If you scroll down, it also shows you the rules inherited (cascaded) from the `.banner` rule:
![Inherited rules]({{<static "images/1.3.6.png">}})
If you scroll clear to the bottom, you will also see a visualization of the [box model](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Introduction_to_the_CSS_box_model) as it is applied to this element.
![Custom style in developer tools]({{<static "images/1.3.7.png">}})
This can be very handy for debugging margin/padding/border issues.
Now scroll back up to the top of the styles tab. Notice the `element.style {}` rule? This displays inline CSS on the element, and we can also add our own inline CSS directly from the developer tools. Add the property key/value pair `text-decoration: none`. Notice what happens to the paragraph's text? Also, notice how the *now overridden* rule has been struck through in the rule below.
![Custom style in developer tools]({{<static "images/1.3.8.png">}})
This can be very handy for quickly trying out different style combinations without needing to add them to the CSS file. Much like changes to the DOM, these are not saved - refresh the page and they are gone.
Finally, notice that when the mouse hovers over a CSS property key/value pair, a checkbox appears next to it? If you uncheck the box, the property ceases to be applied. This can also be very handy for debugging CSS problems.
Now that we've seen how CSS interacts with the DOM tree, it's time to turn our attention to the third web technology - JavaScript.
---
title: "JavaScript and the DOM"
pre: "4. "
weight: 40
date: 2018-08-24T10:53:26-05:00
---
The DOM tree is also accessible from JavaScript running in the page. It is accessed through the global [window](https://developer.mozilla.org/en-US/docs/Web/API/Window) object, i.e. `window.document` or `document`.
Let's use the 'Console' tab of the developer tools to access this object. Open the previous example page again from <a href='{{<static "images/1.3.2.png">}}' target='_blank'>this link</a>. Click the console tab to open the expanded console, or use the console area in the bottom panel of the elements tab:
![The console tab in the developer tools]({{<static "images/1.4.1.png">}})
With the console open, type:
```js
> document
```
{{% notice info %}}
When instructed to type something into the console, I will use the `>` symbol to represent the cursor prompt. You do _not_ need to type it.
{{% /notice %}}
Once you hit the enter key, the console will report the value of the expression `document`, which exposes the document object. You can click the arrow next to the `#document` to expose its properties:
![The reported document object]({{<static "images/1.4.2.png">}})
The document is an instance of the [Document](https://developer.mozilla.org/en-US/docs/Web/API/document) class. It is the entry point (and the root) of the DOM tree data structure. It also implements the [Node](https://developer.mozilla.org/en-US/docs/Web/API/Node) and [EventTarget](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) interfaces, which we'll discuss next.
## The Node Interface
All nodes in the DOM tree implement the [Node](https://developer.mozilla.org/en-US/docs/Web/API/Node) interface. This interface provides methods for traversing and manipulating the DOM tree. For example, each node has a property `parentElement` that references is parent in the DOM tree, a property `childNodes` that returns a [NodeList](https://developer.mozilla.org/en-US/docs/Web/API/NodeList) of all the Node's children, as well as properties referencing the `firstChild`, `lastChild`, `previousSibling`, and `nextSibling`.
Let's try walking the tree manually. In the console, type:
```js
> document.body.firstElementChild.firstElementChild
```
The `body` property of the document directly references the `<body>` element of the webpage, which also implements the [Node](https://developer.mozilla.org/en-US/docs/Web/API/Node) interface. The `firstElementChild` references the first HTML element that is a child of the node, so in using that twice, we are drilling down to the `<h1>` element.
![The reported h1 object]({{<static "images/1.4.3.png">}})
## The EventTarget Interface
Each node in the DOM tree also implements the `EventTarget` interface. This allows arbitrary events to be attached to any element on the page. For example, we can add a click event to the `<h1>` element. In the console, type:
```js
> document.body.firstElementChild.firstElementChild.addEventListener('click', function(e){
console.log(e.target + ' clicked!');
});
```
The first argument to [EventTarget.addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) is the event to listen for, and the second is a function to execute when the event happens. Here we'll just log the event to the console.
Now try clicking on the _Hello DOM!_ `<h1>` element. You should see the event being logged:
![The logged event]({{<static "images/1.4.4.png">}})
We can also remove event listeners with [EventTarget.removeEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/removeEventListener) and trigger them programmatically with [EventTarget.dispatchEvent](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent).
## Querying the DOM
While we can use the properties of a node to walk the DOM tree manually, this can result in some very ugly code. Instead, the [Document](https://developer.mozilla.org/en-US/docs/Web/API/document) object provides a number of methods that allow you to search the DOM tree for a specific value. For example:
* [Document.getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName) returns a list of elements with a specific tag name, i.e. `document.getElementsByTagName('p')` will return a list of all `<p>` elements in the DOM.
* [Document.getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) returns a list of elements with a specific name listed in its class attribute, i.e. `document.getElementsByClassName('banner')` will return a list containing the `<div.banner>` element.
* [Document.getElementById](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById) returns a single element with the specified id attribute.
In addition to those methods, the Document object also supplies two methods that take a CSS selector. These are:
* [Document.querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) which returns the first matching element in the DOM.
* [Document.querySelectorAll](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) which returns a list of all matching elements.
Let's try selecting the `<h1>` tag using the `querySelector` method:
```js
> var header = document.querySelector('h1');
```
Much easier than `document.body.firstElementChild.firstElementChild` isn't it?
## Manipulating DOM Elements
All HTML elements in the DOM also implement the [HTMLElement](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement) interface, which also provides acccess to the element's attributes and styling. So when we retrieve an element from the DOM tree, we can modify these.
Let's tweak the color of the `<h1>` element we saved a reference to in the `header` variable:
```js
> header.style.color = 'blue';
```
This will turn the header blue:
![The blue header]({{<static "images/1.4.5.png">}})
All of the CSS properties can be manipulated through the `style` property.
In addition, we can access the element's `classList` property, which provides an `add()` and `remove()` methods that add/remove class names from the element. This way we can define a set of CSS properties for a specific class, and turn that class on and off for an element in the DOM tree, effectively applying all those properties at once.
## Modifying the DOM
We can create new elements with the [Document.createElement](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) method. It takes the name of the new tag to create as a string, and an optional options map (a JavaScript object). Let's create a new `<p>` tag. In the console:
```js
> var p = document.createElement('p');
```
Now let's give it some text:
```js
> p.textContent = "Tra-la-la";
```
Up to this point, our new `<p>` tag isn't rendered, because it isn't part of the DOM tree. But we can use the [Node.appendChild](https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild) method to add it to an existing node in the tree. Let's add it to the `<div.banner>` element. Type this command into the console:
```js
document.querySelector('div.banner').appendChild(p);
```
As soon as it is appended, it appears on the page:
![The new p element]({{<static "images/1.4.6.png">}})
Note too that the CSS rules already in place are automatically applied!
\ No newline at end of file
---
title: "Chapter 0 Introduction"
pre: "1."
weight: 10
title: "Responsive Web Design"
pre: "5. "
weight: 50
date: 2018-08-24T10:53:26-05:00
---
Lorem Ipsum
---
\ No newline at end of file
+++
title = "Chapter 1 Title"
title = "Web Application Foundations"
date = 2018-08-24T10:53:05-05:00
weight = 10
chapter = true
......@@ -8,6 +8,6 @@ pre = "<b>1. </b>"
### Chapter 1
# Chapter Title Here
# Web Application Foundations
Chapter 1 tagline
Digging Deeper into Core Web Technologies
---
title: "The Event Loop"
pre: "2. "
weight: 20
date: 2018-08-24T10:53:26-05:00
---
Node adopts an asynchronous event-driven approach to computing, much like JavaScript does in the browser. For example, when we set up a HTTP server in Node, we define a function to call when a HTTP request (an event) is received. As requests come in, they are added to a queue which is processed in a FIFO (first-in, first-out) manner.
![JavaScript Event Loop](.guides/img/browser-event-loop.png)
In addition to events, Node implements many asynchronous functions for potentially blocking operations. For example, consider file I/O. If you write a program that needs to read a file, but when it attempts to do so the file is already open in another program, your program must wait for it to become available. In the meantime, your program is _blocked_, and its execution pauses. A real-world analogue would be a checkout line at a store. If the cashier is ringing up a customer and finds an item without a price tag, they may leave their station to go find the item on the shelves. While they are away, the line is _blocked_, everyone in line must wait for the cashier to return.
There are two basic strategies to deal with potentially blocking operations - multi-threading and asynchronous processing. A multi-threading strategy involves parallelizing the task; in our store example, we'd have additional cash registers, cashiers, and lines. Even if one line is blocked, the others continue to ring up customers. In contrast, asynchronous processing moves the potentially blocking task into another process, and continues with the task at hand. When the asynchronous process finishes, it queues its results for the main process to resume. In our store example, this would be the cashier sending another employee to find the price, suspending the sale on the register, and continuing to check out other customers while the first customer waits. When the other employee returns with a price, the cashier finishes checking out the current customer, then resumes the first customer's transactions.
Node uses this asynchronous model to handle most potentially blocking operations (and often provides a synchronous approach as well). When possible, the asynchronous process is handled by the operating system, but the Node runtime also maintains a pool of threads to farm tasks out to.
The Node event loop is divided into a series of phases - each queues the associated kinds of events and processes them in a round-robin fashion. This helps ensure that one kind of event can't overwhelm the system:
![JavaScript ](.guides/img/node-event-loop.png)
For a more detailed breakdown of the Node event loop, check out [this blog post](https://medium.com/the-node-js-collection/what-you-should-know-to-really-understand-the-node-js-event-loop-and-its-metrics-c4907b19da4c) by Daniel Khan or the [Node Event Loop Documentation](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/).
---
title: "Asynchronous Functions"
pre: "3. "
weight: 30
date: 2018-08-24T10:53:26-05:00
---
The benefit of the asynchronous approach is that all user-written code runs in a single-threaded environment while avoiding blocking. This means for the most part, we can write code the way we are used to, with a few tweaks for asynchronous functions.
Consider the two approaches for reading and printing the contents of a file, below:
```js
// Synchronous approach
var data = fs.readFileSync('file.txt');
console.log(data);
// Asynchronous approach
fs.readFile('file.txt', function(err, data){
console.log(data);
});
```
In the synchronous function, the contents of the file are _returned_, and assigned to the variable `data`. Conversely, in the asynchronous approach the file contents are passed into a _callback_ function that is invoked when the asynchronous process finishes (and when the callback phase of the Node event loop is reached). The function itself returns nothing (`undefined` in Node). The important difference between the two is in the first approach, the program waits for the file to be read. In the second, the program keeps executing lines of code after the asynchronous call, even though the file hasn't been read yet.
## Asynchronous Callback Structure
In most Node libraries, the callback function provided to the asynchronous function follows the same format - the first parameter is an error value, which will be populated with text or object if an error occurred, and otherwise will be a __falsey__ value (a value that evaluates to false, like `false`, `null`, `undefined`, or `0`). Successive arguments are the data the function was intended to retrieve - i.e. the contents of the file in the above example. Of course, if an error _was_ encountered, the later values may be wrong. Thus, most programmers follow the pattern of checking for an error at the start of the callback, and halting execution if one is encountered. Rewriting the example above, we would see:
```js
fs.readFile("file.txt", function(err, data){
if(err) return console.error(err);
console.log(data);
});
```
If `err` is a __truthy__ value (any non-falsey value, in this case an Exception object or a string), we log the error to the console and return, halting execution of the rest of the function.
## Common Asynchronous Misconceptions
It is very important to understand that the callback is _executed at a future point in time_, and execution continues to further lines of code. Consider this example:
{Check It!|assessment}(free-text-auto-1698266956)
---
title: "Promises"
pre: "4. "
weight: 20
date: 2018-08-24T10:53:26-05:00
---
\ No newline at end of file
---
title: "Async and Await"
pre: "5. "
weight: 50
date: 2018-08-24T10:53:26-05:00
---
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment