Preventing Express.JS HTTP requests from being blocked by npm cron

I'm experimenting with the cron module from npm within my Express.js application.

The structure of my app is quite straightforward. I have a function to establish a connection to the database, where I then register all the different modules that handle HTTP requests. Here is an example:

import { Router } from 'express';
export default ({ config }) => {
    let api = Router();

    connectAllDbs(config, ({mysql}) => {

        userModule({api, config, mysql});
        // other modules...
    });

    return api;
};

After loading these HTTP modules, I added a cron job which relies on a database connection as well:

const cron = new CronJob('* */30 * * *', () => {
    // perform actions with mysql
});
cron.start();

Since adding the cron job, some of the HTTP requests sent to the node server are intermittently stuck in a 'pending' state in the browser.

https://i.sstatic.net/YFpIB.png

In response to this issue, I began researching child processes and worker threads. However, integrating these features seems complex since the external file now exists outside of my babel-enabled codebase. This requires additional configurations in package.json to incorporate a script beyond index.js...

Is this behavior typical when using the cron module? Despite checking the README and known issues list, it appears no one else has reported similar problems. This leads me to believe I might be overlooking something - any insights on what that could be?

Answer №1

My approach to this issue involved utilizing child_process.spawn.

In order to incorporate the babel setup through npm without creating a separate entry point in the package.json file, I implemented a conditional block within the current entry point (index.js) script, as shown below:

//--------------------------------------------------
// Run the CRON
//--------------------------------------------------
if(process.argv.includes('cron')) {
    runCron();
}
//--------------------------------------------------
// Handle HTTP requests
//--------------------------------------------------
else {
    // Start express -------------------------------
    let app = express();
    app.server = http.createServer(app);

    // Fork the cron process -----------------------
    const spawned = spawn('npm', ['run', 'cron']);
}

While ideally, I would have preferred a distinct second entry-point, I found this solution to be the most straightforward for my current needs.

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

What is the best way to extract a particular key value from a JSON object?

I am completely new to the world of APIs and just starting out with JavaScript. My goal is to retrieve the status of a server from a server hosting panel using an API. In order to achieve this, I need to log in by making a request to /API/Core/Login, extra ...

The error message "require is not defined in React.js" indicates that the required dependency is

As I delve into React coding, the following lines are a part of my code: var React = require('react'); For setting up React, I referred to tutorialspoint. The installation directory is set to /Desktop/reactApp/. My React code is executed from ...

Unable to utilize a third setState function due to the error message indicating an excessive number of re-renders

My current challenge involves setting an initial state for my Hook. I have a clickable element that changes the state between Decreasing and Increasing upon click, and this part is functioning properly. However, I encounter an issue when attempting to defi ...

Getting rid of the empty spaces between the lines of cards in Bootstrap 4

I want to eliminate the vertical space between the cards in my layout. Essentially, I want the cards to maximize the available space. I am open to using a plugin if necessary, but I have not been able to find any relevant information online (maybe I used t ...

Leveraging *ngFor to extract HTML content from ion-label

I've encountered an issue while using *ngFor in my HTML like this: <ion-slides #slides [options]="slideOpts"> <ion-slide class="numbers-wrapper" *ngFor="let questionNumber of numbers" (click)="clickQue ...

The index.js file in ReactJs is failing to run completely

A couple of months back, I delved into the world of React but eventually put it on hold. Today, I decided to pick it back up and took the following steps: npm init npm install npm start Everything seemed to run smoothly (No Errors), but strangely nothing ...

Google app engine continues to experience frequent restarts of PM2

While my app runs smoothly locally with PM2 v 3.5.0, I encounter an issue when deploying it on Google GCP app engine Flex environment. PM2 keeps restarting the app. Below is my PM2 config file: { "apps": [{ "name" : "prod_client", "scrip ...

Is there a way for me to implement this code to achieve the functionality shown in the demo link

$('select').change(function() { var sum = 0; var sum = parseInt($('select[name="bathrooms"]').val() * 25) + parseInt($('select[name="bedrooms"]').val() * 8); $("#sum").html(sum); }); <script src="https://ajax.googleap ...

Storing the path of a nested JSON object in a variable using recursion

Can the "path" of a JSON object be saved to a variable? For example, if we have the following: var obj = {"Mattress": { "productDelivered": "Arranged by Retailer", "productAge": { "ye ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

Express encountering a problem while rendering a new page following a fetch request

Issue with Fetching and Rendering DataURL I have configured an HTTP fetch request from the client side to send JSON data (a dataURL from a canvas) to the server. However, I am facing an error while trying to access it on the server side and render a new p ...

Node application showing no output

I've been attempting to run a basic node application using nide modules and testing it with the Advance Rest Client. Although the console isn't displaying any errors, I'm not receiving any output. https://i.stack.imgur.com/jhf0i.png https: ...

Mastering socket emission and disconnection in reactjs

When using the onchange function, I am able to open a socket and emit/fetch data successfully. However, a new socket is opened on any event. I need to find a way to emit data from the same socket ID without opening a new socket each time. Could you pleas ...

The state object in Redux Toolkit remains static, resulting in the error message "Uncaught TypeError: Cannot assign to read only property 'property-name' of object '#<Object>'"

I'm facing an issue where I am trying to update the data of a state object in Redux Toolkit but it's not changing, and instead throwing an error that says Uncaught TypeError: Cannot assign to read only property 'status' of object ' ...

What is the process for importing DataTables using npm?

My attempt to import "datatables.net-select" using the usual method doesn't seem to be working. After checking the website, I found that the correct way to do it is: var $ = require( 'jquery' ); var dt = require( 'datatable ...

Securing user data after authentication: Best practices for authorizing access

Currently, I am delving into the world of authorization and authentication for my Node.js / Express.js application. In this particular case, my goal is to verify and recognize a user, followed by retrieving data from my database that corresponds with said ...

I am having trouble passing a variable into the AJAX URL using JavaScript

Currently, I am attempting to remove an item from mongodb. However, I am encountering difficulty passing the id into the URL through the ajax call. Below is my code: $(".delete-item").on('click', function(e, id) { var deleteName = ...

Steps to initiate my selenium-standalone server: Execute the command "selenium-standalone start"

I'm currently facing a challenge while trying to execute a test script in WebDriverIO. After cloning the code from wdio-cucumber-framework, I am unable to get selenium-standalone to start properly. The error message indicates an issue with geckodriv ...

Ways to activate a button action with jQuery even when it is disabled and clicked

Thank you for the responses. To clarify my goal, I want the form button to submit all select field responses for processing through php on the next page. If a user clicks the submit button before selecting an option in each field, it should display "whoa d ...

Steps for modifying the CSS style of a div element following an onclick event:

<html> <head> <style type="text/css"> .step_box { border: 1.0px solid rgb(204, 204, 204); border-radius: 10.0px 10.0px 10.0px 10.0px; } .step_box:hover{ background: rgb(184, 225, 252); } .selected { background-color : #fff000; ...