What is the best way to pass a variable between different modules?

I'm currently working with Node.JS and Express.js, and I am facing a challenge of sharing a variable between different modules. The variable in question is a pool of MySQL connections, which initializes 3 connections at the beginning of Node.js execution. My goal is for other modules to utilize these existing connections without creating additional connection pools.

Is there a solution available for this situation?

Thank you

Answer №1

There are a couple of ways to handle this:

  • One option is to declare the variable as global, for example: global.MySQL_pool = .... This will allow you to access it from anywhere in your code by simply using MySQL_pool.
  • Another approach is to pass the variable as a parameter to each module where it is needed, like so:

    var MySQL_pool = ... var my_db_module = require('./db')(MySQL_pool);

The db.js file would look something like this:

module.exports = function (pool) {
  // In this function, you can now access the MySQL pool using the pool parameter
}

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 a fast way to determine if it's necessary to run npm install for

In the following script, it will iterate through all folders and install dependencies var fs = require( "fs" ), path = require( "path" ), child_process = require( "child_process" ); var rootPath = "./"; var dirs = fs.readdirS ...

A guide on utilizing zlib and nodejs to effectively compress and decompress a .tar.gz file

While some may consider this question to be simple, I find myself in need of compressing a folder into a .tar.gz file using only Node's zlib library. Equally important, I also need to decompress the .tar.gz file to a specific destination folder - all ...

Tips for integrating a fresh element into my JSON reply with node.js

Here is the JSON response I have: [ { lat: '53.46424526', lng: '-8.00847728' }, { lat: '53.13914933', lng: '-8.93006114' }, { lat: '53.34009165', lng: '-8.24123887' }, { lat: '53.2725 ...

Leveraging passport.js and direct SQL queries for authentication purposes

Currently tackling a project with an issue that needs resolving. I am looking to integrate user login logic utilizing the Passport API, but struggling to grasp its functionality, especially when implementing it using plain SQL queries. While scouring thr ...

Why is it necessary to use "new" with a Mongoose model in TypeScript?

I'm a bit confused here, but let me try to explain. When creating a new mongoose.model, I do it like this: let MyModel = moongoose.model<IMyModel>("myModel", MyModelSchema); What exactly is the difference between MyModel and let newModel = ne ...

error message: "node-express encountering an excess of redirects"

I have configured my routes as shown below: Upon navigating to 'http://localhost/', I encounter an error message stating 'localhost redirected you too many times'. The URL displayed in the browser's address bar is http://localhost ...

Using the concept of method chaining in JavaScript, you can easily add multiple methods from

Hey there! I'm looking for some assistance with dynamically building a method chain. It seems like it should be pretty straightforward if you're familiar with how to do it... Currently, I am using mongoose and node.js to query a mongo database. ...

Obtain the .exe file containing SailsJS and NodeJS framework

I recently developed a compact application with Node-WebKit. Now, I am looking to establish a backend service using SailsJS that can facilitate downloading an executable file of my app from a remote server. Can someone guide me on how to create this servic ...

redirecting from an AJAX request

Seeking a way to perform a redirect following an ajax `put` request. My intention is to implement client-side validation using pure JS. Client: $(document).ready(function() { login = () => { var username = $("[name='username']"). ...

Is it possible to manually change the IP address in Universal Analytics?

I can't figure out where to specify the IP address override. This library mentions using ipOverride or uip, but it doesn't provide details on the exact location. "universal-analytics": "^0.4.20" Below is my code without overriding the IP addres ...

Steps to customize a CSS file within node_modules

Is there a way to make changes to a CSS file in the "node_modules" dependency without them being overwritten when I run npm install? I want to keep the modifications I've made to the node module files. ...

When I run "gulp serve," I receive the error message: "Uncaught ReferenceError: primordials is not defined."

Today marks my first day diving into the world of SPFx, Gulp, and Yo. I decided to follow a tutorial, but encountered a major error that's preventing me from moving forward: mini-3:helloworld-webpart admin$ gulp serve ReferenceError: primordials is no ...

unraveling JSON in Node.js

I am encountering an issue with accessing the 'column' in my JSON data below. I keep getting 'lowerdeck' as undefined. Can someone please assist me in resolving this problem? { "errorcode": "0", "xml": { "seat-map": { "lo ...

Is the sequence of routes significant in the Express framework?

Currently, I am in the process of creating a straightforward CMS with Restfull routes using Express.js. Initially, everything was running smoothly. However, when I attempted to make some adjustments to tidy up my routes, specifically by rearranging the rou ...

What is the best way to identify a specific pattern within a string using regular expressions in JavaScript?

Looking for a way to extract specific values from a string? let temp = 'Hi {{username}}, Your request with request id: {{requestId}} has been processed. Please contact your nearest shop.' Desiring an array like this from the string: ['user ...

Why is it that I am limited to running globally installed packages only?

Recently, I made the switch to Mac iOS and encountered an issue while setting up a new TypeScript backend project. All npm packages seem to be not functioning properly in my scripts. Cannot find module 'typescript/bin/tsc' Require stack: - /Users ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Transform a protractor screenshot into a PDF file

I'm currently working on a small Protractor code that captures screenshots, but my goal is to save these screenshots as PDF files. Below you can find the code snippet I have written. await browser.get(url); const img = await browser.takeScreenshot(); ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

The specified version of Mongodb in the package.json file is encountering difficulties during the installation

If the command npm install mongodb is executed, the desired version of mongodb gets installed successfully: - email protected node_modules/mongodb/node_modules/bson email protected] /home/lorencm/Downloads/mongo-invoices └─┬ email protected] ├ ...