TIL/2021–01–15&16

Renzo Regio
9 min readJan 25, 2021

Day 35 and 36: Treehouse Full Stack JavaScript Techdegree

For these two days, I learned about Node.js

Node can be used to build all sorts of applications — from web applications deployed on the internet to desktop and command line applications that you can run on your local machine

Each command line application will go to the web, retrieve information and print out information on the console

Examples that use node js:

Before, walmart used to have issues on their website during black friday. But now it doesn’t have any issues because it moved to using node.js

Paypal serves 80% of its web traffic using node.js

— — -

Hello world

Node.js is a terminal based application

.error() — ideal for logging out error messages

.dir() — receives an object and prints out the values and keys in a human readable format

Node also allows you to experiment JavaScript on the terminal

> is called a read evaluate print loop or REPL

As it reads the code you enter, it evaluates it or runs it and then prints it out

— -

JavaScript without the browser

Native Objects: objects provided by the JavaScript Programming language

  • String, array, date, Math and more
  • Can be used in any environment, not just in the browser

Host objects: Objects provided by the environment

  • Window, history, XMLHttpRequest, Document

When chrome’s v8 became open source, it became the perfect environment for something new to appear, something to write any type of general purpose application in JavaScript — and that was node.js

Ryan Dahl retrieved the Chrome’s v8 JavaScript engine out of the browser leaving all the browser’s host objects behind and provided new ones to allow for the new types of applications to be written

  • Http
  • Https
  • fs — file system
  • url
  • os

The coupling of the v8 engine with the APIs is known as Node.js or the Node.js environment

JavaScript applications are now free to run stand alone on a personal computer or even on the internet running on the server

— —

Why use Node.js?

Most languages on the server-side handles one set of tasks from beginning to end (assistant analogy) before repeating the process again doing the same set of steps for another task

Imagine having a social network that has a sign up, imagine how frustrated the user would be if they would need to wait for all the images to load first before being able to actually sign up or interact with the web page.

Languages that queue up requests and processes them one at a time are known as blocking languages — since it blocks the handling of other requests

Developers scale these types of applications by running more than one instance of their web applications — these instances are called workers

Node.js works as a more efficient assistant. Doing what it can do now, responding to requests while it waits for other tasks to finish — Being able to handle multiple events or user actions at the same time.

Sometimes one Node.js worker is more responsive than other languages

Node.js is non-blocking and that is why we would want to build JavaScript on the Node.js platform — it is fast and efficient, it doesn’t take up as many computer resources by the computer processing power or memory

— —

Finding help as a Node.js developer

https://nodejs.org/api/

Stick to stable and locked APIs (Application Programming Interface)

File system: where the APIs to read and write are found

HTTP and HTTPS: for creating web servers or going out to the internet to retrieve information

A lot of built-in node.js APIs require callback functions — provide a callback for system events

https example:

In this example, response has a system event called ‘data’ associated with it. Then the callback prints out a piece of data

System events are processed by the computer and not by a user interaction

— -

In the Node.js documentation I can use the stability index to determine which APIs to use

Stability Index 0 means deprecated

Node.js is non-blocking — node.js can perform other tasks while it waits on other tasks to complete

If I type node on the console, an interactive repl (read-evaluate-print-loop) would start and allows us to experiment interactively with JavaScript

— —

4 p’s of problem solving

  1. Prepare: diagnose a problem and propose a solution
  2. Plan: plan the solution — write comments on the JavaScript file
  3. Perform: perform the required actions from the planning phase(write the code)
  4. Perfect: Incrementally improving the project — find any errors in the project and handle them

API (Application Programming Interface): Allows you to programmatically interact with another program

— -

System Events:

Types of Events:

  • User events: mouse click — the user is what triggers it
  • System events: setTimeout() function — the system is what triggers it

Onreadystatechange — the ready state change handler gets triggered by the system when it goes through different stages of the request

System events in node.js

  • Data events (reading data from a url)
  • Completion actions (When an action is completed
  • Various error handling events

— — -

Making a get request with Https:

— —

Getting the response body

The response object has a data event that gets emitted in once a piece of data comes in

Runs several times with only fragments of the body — it is not a string but a buffer, a common data type emitted by the node network and file events

When something is sent over the network like the internet, it is not sent in one go. It is sent in packets of information, many programming languages or frameworks, wait until all data is transmitted before you can do anything. However, node.js uses streams to implement its non-blocking features. So your application is free to do other things while waiting for the data to come in.

To convert a buffer into a string, call the toString method on the buffer

And this is what we get

They emit a data event and a chunk of data comes in. And then it emits an end event when it’s completed reading the data in.

Basically we are implementing the end handler and once the end handler executes, it prints out the whole body and the type of the body which is a string

— — -

Parsing JSON

We have the string printing out but we want to access the properties programmatically

We want to convert the string into an object

The process of converting a string into a data structure is called parsing

Json is a native object in the environment

JSON.parse(string) — you can pass in a string to get parsed as a JSON object

We can use console.dir() to figure out the values we need

example:

— —

Capturing command line arguments

Let’s implement the feature of getting information from multiple treehouse students from the command line as arguments to our script

Right now we have the username fixed as a constance

We have to change that.

We can wrap the process into a getProfile function and just add the username every time we call it on the app.js file

In this example, chalkers was first called with getProfile and then allena. But allena was printed first because she has less badges, meaning that her profile gets processed faster. This is an example of how node is non-blocking. Since it didn’t process one by one but both simultaneously.

Instead of doing this we can put the users in an array so that we don’t have to repeat ourselves saying [getProfile] and adding the username each time.

And it would work the same way.

Or even shorter — since we are only passing one parameter on get profile

But how can we do (on the cli)

node app.js renzoregio chalkers

And get the exact same result

There is a global host object for node.js called process and we can see its properties by logging it to the console

We can use it by adding the array property called argv

process.argv

This gets us the app.js ,node binary and the two users we put as arguments, we don’t want the first two so we can use the slice method

And it logs the two usernames

const users = process.argv.slice(2) // returns an array with the username, process returns an array with the node binary and app.js plus other arguments

Total Code:

— — -

What is the global object we can access the current version of node and arguments passed in the command line? process

The command line arguments can be accessed through which property on the ‘process’ object? Argv

— — —

Handling the error event in node

Many asynchronous Node.js APIs gives you an error event to listen to. If you don’t implement the error callback there can be some issues

We are going to make an error by adding www on the url without the .

And when we run it there’s an error:

We can capture the error by implementing an error handler for the event

Request — which is the request to the API

.on — on an event

There is another type of error that can happen — from the developer’s perspective

If we incorrectly pass in a URL when making a request that doesn’t comply with the URL specification — for example the protocol is missing

We will get a stack trace that says ‘Unable to determine the domain name’

This is because in Node’s code design philosophy is if you pass in bad arguments to the node API it should throw immediately

If you pass in good arguments but it fails during runtime then an error event is emitted

So when we pass a malformed URL like the one above, we have to use a try and catch block

--

--