The life cycle of the request/response object in Express.js when using callbacks

Feel free to correct me if this question has already been asked. (I've done as much research as I can handle before asking)

I'm really trying to wrap my head around the life cycle of request and response objects.

Take a look at the following code snippet:

app.get('/', function(req, res) {

  var setCookie = function(err, idCookie) { //callback after cookieSearch in DB
    // ... do something with the result of findCookieInDatabase() (handle error, etc.);
    res.sendfile('index.html');
  }

  var cookie = parseCookie(req.get('Cookie')); //parse and format cookie

  findCookieInDatabase(cookie, afterCookieSearch); //tries to find cookie is DB


  // .. do some content return stuff, etc.
}

(Please be aware that the actual code does much more, including checking if 'Cookie' even exists etc.)

I know that req and res objects are created and eventually have to be garbage collected. (At least I hope so)

When findCookieInDatabase() is called with setCookie as an argument, I understand that setCookie is just a string (containing the function) until the callback(setCookie) statement is reached in findCookieInDatabase().

I also realize that I could be completely mistaken in my assumption above, which might be due to my lack of understanding of javascript callbacks. (I've searched extensively on this topic but only found endless tutorials on how to use callbacks, nothing about what goes on behind the scenes)

So here's my question: How does javascript (or node.js) determine how long to keep 'res' alive and when it's safe to garbage collect it?

Does the line res.sendfile in setCookie serve as an active reference because it's invoked through findCookieInDatabase()?

Does javascript actually monitor all references and keep req and/or res alive for as long as any part of any callbacks or other functions are still running?

Any assistance would be greatly appreciated. Thank you for reading.

Answer №1

If you are feeling overwhelmed by your code and assumptions, it might be time to revisit some JavaScript fundamentals. Expand your knowledge by exploring these recommended books:

  • Check out Speaking JavaScript by Axel Rauschmayer
  • Dive into JavaScript: The Good Parts by Douglas Crockford (note: not everything Douglas Crockford says is gospel, but this book is essential for aspiring JavaScript developers)
  • Explore Learning Node by Shelley Powers

Don't forget to also take a look at my own book, Web Development with Node and Express. Now that we've covered the reading material, let's delve into solving the core of your issue.

When an HTTP request reaches Node, it generates the req and res objects (originally instances of http.IncomingMessage and

http.ServerResponse</code). These objects are designed to exist throughout the duration of the HTTP request cycle. Following the client's request, various activities occur, culminating in invoking a method on <code>res
to return an HTTP response to the client, after which these objects become unnecessary.

Due to Node's asynchronous nature, multiple instances of req and res can coexist, differentiated only by their respective scopes. This concept may seem intricate; however, in practice, it's generally inconsequential because when writing code, you treat each instance uniquely without concerning yourself about managing multiple requests as frameworks like Express handle such complexities.

Javascript employs a garbage collector whereby objects get deallocated once their reference count diminishes to zero. As long as there exists a reference to a particular object such as req, that object remains intact. Consider this rudimentary example involving a flawed practice within an Express program:

An array named “allRequests” purposely maintains all user requests.
app.use(function(req, res, next) {
    allRequests.push(req);
    next();
});

Nevertheless, failing to remove items from allRequests could lead to memory exhaustion while processing traffic.

In Express, asynchronous functions play a pivotal role by executing callbacks post tasks completion. If said callback holds references to req or res objects, these objects remain unchanged until the function finishes its duties and the callback executes (alongside exiting other relevant scopes). For instance:

A brief demonstration showcasing delays:
app.get('/fast', function(req, res) {
    res.send('fast!');
});

app.get('/slow', function(req, res) {
    setTimeout(function() {
        res.send('sloooooow');
    }, 3000);
});

Accessing /slow results in a 3-second delay, whereas repeatedly visiting /fast showcases uninterrupted functionality. Each request in Express generates distinct req and res objects, maintaining segregation. Yet, the associated res object linked to /slow is retained due to its pending callback execution.

Remember, understanding the foundational concepts is crucial; nonetheless, grappling with counting references and managing garbage collection in Javascript is often needless. Take a breather and trust that these mechanisms operate seamlessly in the background.

I trust this elucidates your concerns.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Excessive ajax requests occurring when the options in the form are altered

My website contains two main sections: (1) search criteria, which include selection boxes in a form used to access database information, and (2) a div where the results are displayed. The initial page load serializes default values from the form and sends ...

Retrieving ng-repeat $index with filtering in AngularJS controller

I am facing a challenge with my ng-repeat list and filter in AngularJS. I am unable to retrieve the visible $index value from inside my controller. Although I can display the index easily and see it change dynamically when the list is filtered, I am strug ...

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

Challenges with line height in IE when adjusting font size in textarea

I'm facing an issue with adjusting the font size in a textarea using JavaScript. While it works perfectly in Firefox, there are some problems in IE. Specifically, the line-height does not change accordingly. This results in gaps between lines when the ...

Pull the data from jQuery/JavaScript/AJAX and store it in the database using ASP.NET/C#

I am working on creating a form that includes textboxes and a five star rating feature. The goal is to save the data entered in the fields into a database upon submitting. While implementing the textboxes was straightforward, I am facing challenges with e ...

React.js: The specified element type is not valid:

I am currently working on a sample project using react.js in Visual Studio 2019 Here is my Index.js file: import 'bootstrap/dist/css/bootstrap.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provi ...

Using touch-action to enable movement from the last item to the first item in HTML/C

Currently, I am utilizing the touch-action property in my carousel which auto slides without any issues. However, I am facing a problem where when I scroll using touch-action, it stops at the last slide instead of looping back to the first slide. My goal i ...

Learn the steps to successfully rotate the custom icon in Material-Ui select without impacting its functionality and making sure it remains clickable

I've been trying to incorporate my own icon for the material UI select component. I successfully replaced the default icon using the "IconComponent" attribute in MU select. However, I'm facing issues with the new icon not rotating when the menu ...

Customer Notification System Malfunctioning on Front End

I am currently experimenting with MeteorJS technology and attempting to use alerts for success or failure notifications when making a meteor call. However, I've encountered an issue where the alerts are not functioning as expected. T ...

What could be causing my jQuery script to malfunction?

After scouring through numerous Stack Overflow questions and conducting countless Google searches, I am still stumped by the issue at hand. As a beginner in web development, all I want is for this simple page to function properly. Can someone please point ...

What is the best way to run an external JavaScript file at regular intervals?

I enjoy loading an external JavaScript file every 10 seconds, or whenever the page body is clicked (in which case, the script should only run if a few seconds have passed). If you could provide me with some documentation on this topic, that would be grea ...

Can someone explain to me the meaning of "var vm = $scope.vm = {}" in AngularJS?

While reading through the angularJS api, I came across some code that looked like this: myApp.controller('MyController', ['$scope', function($scope) { var vm = $scope.vm = {name:'savo'}; } ]); Initially, this mul ...

Utilizing a V-for/V-if loop to iterate through a multi-dimensional array and filter data based on date

I'm facing a challenge with setting up a v-for loop for an array I've constructed, which is already in the desired format Below is a snippet representing the data format. Essentially, I want to create a table for employees where the header consi ...

Troubleshooting: Issues with jQuery's clone() function

I'm facing an issue with the code below. It works correctly when I use td instead of p. $(document).ready(function() { $("button").click(function() { $("th:contains('2G Band') ~ p").clone().appendTo("#2g"); }); }); <script src= ...

Emulate sequelize using Jest in combination with sequelize-mock

In my latest project, I have been implementing TDD as the primary methodology along with integration tests. One of the tasks at hand is to retrieve all users from the database. //controller.js const UserService = require('../services/user'); mod ...

Tips for managing unfinished transactions through Stripe

I have successfully set up a checkout session with Stripe and included a cancel_url as per the documentation. However, I am facing an issue where the cancel_url is only triggered when the user clicks the back button provided by Stripe. What I want to achie ...

Is there a comparable Javascript alternative to the Ruby gem "site_prism" for Page Objects design?

Is there a JavaScript framework for Protractor in NodeJS that provides a clean way to define Page Object Elements similar to site_prism? I've explored astrolabe but it doesn't quite meet the requirements. This is an example of how Page Objects a ...

Creating a custom useStorage hook to easily save a Set data type in local storage

I attempted to make modifications to the code found at this reference link: useLocalStorage hook my goal was to enable saving a Set() to localStorage. useLocalStorage.js import { useState, useEffect } from "react"; // Custom Hook export const ...

How to activate a single element within a React array

I am currently working on developing a comment system similar to the one found on YouTube. In my setup, when I click on modify, all comments turn into input fields, but only the selected input should be modified. How can I trigger only the element I clicke ...

Discovering how to identify words separated by spaces within a full-text search query using regex in both PHP and JavaScript

When working with text, I need to detect words that are separated by spaces. For example, if my text is: some parent +kid -control "human right" world I want to only detect some, parent, and world. This means words without any special characters like +, ...