---
# System prepended metadata

title: '2003-GHP Cookie Jar: Node and Express'

---

# 2003-GHP Cookie Jar: Node and Express

Put your pending and outstanding questions here 👇
Make the question in an H2 tag by using '##'

Example:

## What is JavaScript?

## For the question regarding inspecting the Event Loop

## Answer

While there's nothing super "official", you can use something like `process._getActiveHandles()` and/or `process._getActiveRequests()` in Node.

For more [info](https://github.com/nodejs/node/issues/1128)

## There was a question on being able to execute without doing `module.exports`, it was still able to execute

## Answer

This is expected behavior as, by default, node modules export an empty object

## There was a question if we had, instead of nested `setTimeouts`, they were back to back and the second one had a lower time than the first, what would execute first.

## Answer

This is `example-5.js` inside the `async folder`

```javascript=
console.log('Beginning of file')

setTimeout(
    () => {
        console.log('1. Hello, I will be timing out for 4.0 seconds')
    },
    4000
)

setTimeout(
    () => {
        console.log('2. Hello, I will be timing out for 5.0 seconds')
    },
    5000
)

setTimeout(
    () => {
        console.log('3. Hello, I will be timing out for 3.0 seconds')
    },
    3000
)

setTimeout(
    () => {
        console.log('4. Hello, I will be timing out for 2.0 seconds')
    },
    2000
)

setTimeout(
    () => {
        console.log('5. Hello, I will be timing out for 5.0 seconds 2')
    },
    5000
)

console.log('End of file')
```

### Output

```
Beginning of file
End of file
4. Hello, I will be timing out for 2.0 seconds
3. Hello, I will be timing out for 3.0 seconds
1. Hello, I will be timing out for 4.0 seconds
2. Hello, I will be timing out for 5.0 seconds
5. Hello, I will be timing out for 5.0 seconds 2

```

I added an `example-7.js`

```javascript=
console.log('Beginning of file')

setTimeout(
    () => {
        console.log('1. Hello, I will be timing out for 4.0 seconds')
    },
    4000
)

setTimeout(
    () => {
        console.log('2. Hello, I will be timing out for 2.0 seconds')
    },
    2000
)

console.log('End of file')
```

### Output

```
Beginning of file
End of file
2. Hello, I will be timing out for 2.0 seconds
1. Hello, I will be timing out for 4.0 seconds
```

## From the above answers, you would think the setTimeout function with the smaller delay would execute first. However, that's not the case with the example below. What's going on?

```javascript=
console.log('Starting app');

setTimeout(() => {
  console.log('Inside of callback');
}, 2);

setTimeout(() => {
  console.log('Second setTimeout');
}, 0);

console.log('Finishing up');
```

### Output

```
Starting app
Finishing up
Inside of callback
Second setTimeout
```

## Answer

I am, unfortunately, not seeing that in my terminal. Is it consistently your output? 

![](https://i.imgur.com/c6TCBqo.png)


## Some Definitions

- Client: Something that requests resources/data
    - Browser
    - Mobile
    - Desktop App
    - API Testing Tool
- Server: A program that runs on our computer that receives the requests for resources/data
- Protocol: A method of communication between two processes
    - HTTP: The communication method of the internet. Defines how data is formatted and transformed.
- Thread: An operating system's basic unit of execution
- Process: A collection of threads. An executing instance of a program. 
- Process vs. Thread
    - Process
        - Different processes don't share the same memory space
    - Threads
        - Threads within a process share the same memory space
- Compiler: A  program that (generally from high level to low level) translates a language to another language (machine code generally)
- Interpreter: A program that directly executes instructions in source programming language
- Runtime Environment: Gives ability to target machine to be able to execute some type of program
- Operating System: Software that helps the computer do things such as schedule tasks (think about what's going when you're running Slack and VS Code and Google Chrome at the same time) and executing applications

## Overview of the Concepts

### The Point of Node
- Node allows us to create backends for our web apps. It allows us to run JavaScript outside of the browser. It achieves this through packaging the V8 Engine with it. 

### What Are Modules?
- Packaged code in different files. The point is to split up different functionality into different files and `require` them where needed. We use `module.exports` to expose functions or variables from one file.

### Event Loop and Asychronicity
- Our code may run in a different order than it is written in. A good example is `setTimeout`. If JavaScript was blocking, it would wait for the `setTimeout` to finish running before running the next piece of code. 
- JavaScript is non-blocking so that if it encounters a piece of asynchronous code, it will queue up the functions into the event queue and the event loop is responsible for bringing those functions back to our call stack when the call stack is empty. Since, JavaScript does this, we don't need to wait for the asynchronous code as it is running in the background and let's us continuing running code in the foreground.

### What is Express?
- Express is a Node web framework that handles requests. It makes it a lot easier for us to write routes as well as middleware. 

### What are requests? What are responses?
- Requests are sent from a client. HTTP requests contain so many different parts but we really care about, the method (GET, POST, PUT, DELETE), the URL (where the request is going), the params (if we are using parameters)
- Responses are sent from the server. They respond with whatever resources requested by the client, a status code and/or an error message.
- This is all part of the request-response cycle. 1 request; 1 response.

## Expand on the HTTP Verbs
- GET: Request to receive data
- POST: Request to create data
- PUT: Request to modify/update data
- DELETE: Request to delete data

## What is Middleware?
- Middleware is run in between the request and the response. A way we create middleware is `app.use`. We would need to use `next` in middleware to prevent stalling and passing the request along the rest of our application. The process is as follows:
    1. The server receives a request with an HTTP verb, URL, header, etc.
    2. If there is a middleware function, that should run after the request is received and will run at this time
    3. The middleware function runs, does what it needs to do and will pass control to the next middleware function (if applicable)
    4. If there are no middleware functions left, then the control is passed to the route handler.
- [Middleware Documentation](https://expressjs.com/en/guide/using-middleware.html)

## What is `package.json`, `package-lock.json`, `node_modules`
- `package.json` let's us store data about our project as well as stores a list of dependencies for the project. When we do `npm i express`, it will install `express` and put it in the dependencies and all the external dependencies that express needs to run will be stored in node_modules and the data of the dependencies gets stored in `package-lock.json`
- `node_modules` contains all the libraries downloaded from `npm`. Since many of the libraries depend on a lot of other libraries, node_modules will contain them. This should NOT not be pushed to Github and be put into our `.gitignore`
- `package-lock.json` is automatically generated for any operations where npm modifies either the node_modules, or package.json. See more from [docs](https://docs.npmjs.com/files/package-lock.json)

## Why does (a) work but not (b)? I.e. Receive error for console.log(doge) in index.js in (b).
(a)
![](https://i.imgur.com/m1nWSfs.png)

(b)![](https://i.imgur.com/54hNS8p.png)

Follow up question:
- If the require(...) function in index.js just returns the module.exports value from doge.js, why is console.log in doge.js also executed?

## Answer

Great questions.

1. If you do `console.log(require('./doge'))`, then it will work. The return value of the `require` function is the `module.exports`, which in this case is the string, 'Party Doge from doge.js' so the error happens because you're trying to print out `doge`, which doesn't exist. 
2. `require` actually is very intricate behind scenes but the main things that it does:
    1. It reads a JavaScript file
    2. Executes that file (this is where the console.log gets executed)
    3. Returns `module.exports` object (You're not assigning it to anything or printing it out directly hence the error you're getting in point 1)

![](https://i.imgur.com/n87isSU.png)

## I am unable to remove the stack trace in custom error. Can you please explain how to do that?
- You can actually do this if you read the resource below. However, as discussed in chat, you would want to keep the stack trace for the server side for your own debugging purposes and you will want to `res.send` or `res.json` something customized to the frontend for your users to see
- 
- [Stack Trace Resource](https://hackmd.io/9ZYXAd9eS6KkOq3nIlpIUQ?sync=&type=)

## What's happening step-by-step in Express.Router() using this example: http://expressjs.com/en/guide/routing.html#express-router?
My assumptions:
(1) Router is an instance/object of Express.Router()
(2) Attach use and get methods to router or are we calling those methods???
(3) Attach router to module.exports
(4) Attach module.exports to birds
(5) App.use = router.use???


## Answer

I'll start with (5): `app.use` does NOT equal `router.use`. `router.use` middleware will only run for that specifically defined router. So, if we have routes for dogs and cats and we have a `router.use` for cats, it will not run whenever we do requests for dogs. 

As for your assumption.

1. Router is actually a complete routing system (hence being called a "mini app") and middleware so yes when we do the line `const router = express.Router()`, we are saying to create an instance of this mini app.
2. Since it functions exactly how a typical Express routing system works, you are basically creating your routes with whatever HTTP verbs necessary. `.get, .post, .put, .delete, .use` are still all methods we use to declare whatever routes and middlewares we need
3. Yes, we are saying export the router.
4. Yes, as well to this. We are requiring the router module birds and setting it equal to a birds variable.

## Since the sequence matters in the routes we write, how do we decide which route should be placed where?

## Answer

Great question. You should follow the typical REST architecture of

```javascript=
GET /
GET /:id
POST
PUT /:id
DELTeE /:id
```

Another thing: Let's take a look at this code:
```javascript=
app.get('/nyancats/:id/', (req, res) => {
    console.log(req.params.id)
    // console.log(req.params.someId)
    console.log(req.params)
    res.send(`▒▒▒▒▒▒▒█▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀█
    ▒▒▒▒▒▒▒█░▒▒▒▒▒▒▒▓▒▒▓▒▒▒▒▒▒▒░█
    ▒▒▒▒▒▒▒█░▒▒▓▒▒▒▒▒▒▒▒▒▄▄▒▓▒▒░█░▄▄
    ▒▒▄▀▀▄▄█░▒▒▒▒▒▒▓▒▒▒▒█░░▀▄▄▄▄▄▀░░█
    ▒▒█░░░░█░▒▒▒▒▒▒▒▒▒▒▒█░░░░░░░░░░░█
    ▒▒▒▀▀▄▄█░▒▒▒▒▓▒▒▒▓▒█░░░█▒░░░░█▒░░█
    ▒▒▒▒▒▒▒█░▒▓▒▒▒▒▓▒▒▒█░░░░░░░▀░░░░░█
    ▒▒▒▒▒▄▄█░▒▒▒▓▒▒▒▒▒▒▒█░░█▄▄█▄▄█░░█
    ▒▒▒▒█░░░█▄▄▄▄▄▄▄▄▄▄█░█▄▄▄▄▄▄▄▄▄█
    ▒▒▒▒█▄▄█░░█▄▄█░░░░░░█▄▄█░░█▄▄█`)
})

// Experiment with this so we can see that order of the routes matter. 
// If defined after "app.get('/nyancats/:id/",
// It will treat add as a parameter
app.get('/nyancats/add', (req, res) => {
    res.send(`<h1> Hellloooooo </h1>`)
})
```

Just as the comment says: If we define that second route after our `:id` route, it will match the `:id` route and treat add is a parameter. In the second route, we are just trying to define another route in which we can add a new nyancat, so it will be another page of our website.

## I'm still unsure of when to use body parser and when to each of the following (sounds lke gibberish to me):
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded