Why are imported modules unable to reach global variables in Node?

As I delve deeper into using ES6 and organizing my code across multiple files for better readability and version control, I've encountered an issue that has me puzzled. In one of my scenarios, I have a class defined in a separate file called class.js, which is then exported using module.exports. Within my main script, main.js, I require class.js and utilize it to create instances of the class it contains. However, I face a problem when trying to access a global variable called connectedPlayers from within one of the methods in class.js.

The method in question, usersOnline(), is intended to simply return the value of connectedPlayers. But when I attempt to do so, I receive an error stating that connectedPlayers is not defined. My expectation was that since the object calling usersOnline() was created in main.js, the method should look for connectedPlayers within main.js rather than class.js. Is this line of thinking correct? If so, why am I unable to access connectedPlayers? And if not, what is the correct approach to accessing global variables within my class?

In reality, I have multiple global variables in main.js that need to be accessed by methods inside class.js. These variables are subject to frequent changes, making it impractical to pass them into the constructor or provide them for each method call. Is there a more efficient way to achieve this?

To further elaborate, I aim to replicate the functionality akin to how imports work in browser JavaScript – where imported code acts as though concatenated with the importing code. While I understand this concept doesn't directly translate to Node.js, my assumption was that creating an instance of my class within main.js would allow the methods from that object (which reside within the scope of connectedPlayers) to be executed properly. However, it seems my understanding may be flawed.

Pseudocode:

//class.js
class user{
    constructor(id){
        this.id = id;
    }

    someOtherMethod(){
        ...
    }
    
    usersOnline(){
        this.someOtherMethod(this.id); //showcasing the necessity for context to remain intact
        return connectedPlayers;
    }
}

//main.js
var user = require('class.js');
var players = {}
var connectedPlayers = 0;

players[id] = new user(id);
console.log(players[id].usersOnline()) //expects to return the value of connectedPlayers while executing other functions within usersOnline correctly.

Though in this example moving player count into class.js could resolve the issue, such a solution proves unfeasible for my actual application.

Answer №1

It would be beneficial to see some code examples, but based on my understanding, you may have something like pseudocode below:

export class Class{
  constructor(){
    this.name = "foo";
  }
  usersOnline(){
   return main.connectedPlayers();
  }
}

-----

require('Class.js');

function connectedPlayers(){
  // stuff...
  return [Object]
}

...
var class1 = new Class();

console.log(class1.name); // correctly outputs "foo"
console.log(class1.usersOnline()); // returns main not defined

The issue arises because the 'class.js' file does not refer back to the main class. Simply initializing an object in 'main.js' doesn't automatically make it aware of its surroundings. You have to explicitly specify which environment the object belongs to upon creation. One common approach is passing the 'context' of the main class during instantiation. (different approaches can yield varying results)

constructor(context){
  this.name = "foo";
  this.main = context;
}

---

var class1 = new Class(this);

With this adjustment, the class is now aware of where it belongs when executing its usersOnline() method.

Note that there are more refined methods for achieving this than the one I've outlined here. The approach I've described serves as a basic demonstration of the concept commonly implemented in more sophisticated ways. View this answer for alternative techniques and additional resources.

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 transfer Kendo Grid row data to a Kendo popup window within a partial view using jQuery?

I am currently facing a challenge in passing the row data from the Kendo Grid to a partial view that is displayed through a Kendo popup window. Within the partial view, users have the option to upload an image file related to the specific row record. This ...

Having trouble retrieving the .html() content from the <label> element

Check out the code below: $('.size_click').click(function () { $(this).closest('span').toggleClass('active_size'); $('.selected_sizes').append($(this).closest('label').html()); }); There are multiple ...

When adding values, they remain in their original positions

I am populating a select dropdown with options using AJAX. These options are added based on the selection made in another dropdown. The first function that appends the data: var appendto_c = function(appendto, value, curcode) { appendto.append("& ...

Issues arise with AngularJS showing images fetched from an API

Currently, I am facing an issue where I am trying to display images from a REST API but keep receiving a "error 403" message. Here is the link to my JSFiddle. Please take a look, as I have attempted using both <img src=""> and ng-src='', bu ...

Using CSS properties as false values within React applications

Can you provide guidance on using conditional styles with conditional operators? What would be the ideal code example? Is it possible to use non-CSS values? margin: isOpen ? '10px' : undefined margin: isOpen ? '10px' : 'initial&a ...

The counterpart to Ruby's `.select{ |x| condition }` in Javascript/ React.js would be to

This javascript function in React.js utilizes a for loop to determine the opponent team: getOpponentTeam: function(playerTeamId){ var matches = this.state.matches; var player_team = this.state.player.team.name for (i in matches){ if (matches[i]. ...

Unlinked CSS File in NodeJs To-Do List

I'm working on a Todo List project using nodeJs, and I'm struggling to connect the CSS file. I've added the CSS file in header.ejs and included it in list.ejs file, but for some reason, the CSS file is still not being linked properly. ...

"Encountered a problem during installation of the zmq module in Node

Encountered an error when attempting to install the zmq package in Node.js: npm http GET http://registry.npmjs.org.org/zmq npm http 200 http://registry.npmjs.org.org/zmq npm ERR! registry error parsing json > <a href="/cdn-cgi/l/email-protection" c ...

Error: The variable <something> has not been defined

Within my GitHub project, an error stating Uncaught ReferenceError: breakpoints is not defined is appearing in the Chrome console. This issue should be resolved by including breakpoints.min.js, but it seems that webpack is somehow causing interference. I ...

Vue - Error Message from Eslint Regarding Absence of Variable in Setup Function

Interestingly, the Vue.js documentation strongly recommends using the <script setup> syntax of the Composition API. The issue with this recommendation is that the documentation lacks depth and it conflicts with other tools (like eslint). Here is an e ...

Deploying PhantomJS on Heroku

Running a node app on Heroku has been smooth sailing for me. I've implemented web scraping through selenium in Python, where my python script is called from the node app whenever needed. When testing locally on my Mac, everything functions perfectly a ...

Error message: "We apologize, the name must only consist of characters that are compatible with URLs."

Currently, I am following a tutorial on Angular 12 that can be found at . However, I am facing an issue with executing the command below: npm install express cors body-parser mongoose Here is the code snippet: PS D:\VArdhan\projects\node-an ...

Rendering a component and updating state with inline onClick event handlers

When discussing the concept of pure render methods in React and highlighting the serious anti-pattern of setting state inside the render function, how strictly should this be adhered to? It is understood that triggering a setState within the render functio ...

Utilizing parameterized routing to direct traffic to the /userid endpoint instead of the literal /{user id}

My setup includes a router with the following routes: router.get('/', index_controller.index); router.get('/login', index_controller.login) router.get('/profile/:userId', index_controller.profile) I have two controllers that ...

Experience the power of SSR Nuxt.js with a seamlessly integrated REST API backend

Currently, I am working on developing a SSR Nuxt.js application that integrates with a REST API server. In order to achieve this, I have included my endpoint /api into the Nuxt server.js code as shown below: const express = require('express') c ...

By clicking the button, you can add an item to select2

Utilizing the select2 tag style in my Drupal YAML form allows users to easily locate and add various items. These items come with both images and titles on the same page, accompanied by a button next to each image. My goal is to enable users to click the b ...

Executing jQuery script on dynamically loaded content

My website utilizes AJAX requests to load pages dynamically. One specific page includes a marquee script that I would like to implement. Unfortunately, due to the dynamic loading of the page, the marquee script is not functioning as expected. I have come ...

Using JavaScript: How to utilize Array.reduce within a function that also accepts arguments

let foo = 0; let bar = 0; const arr1 = [1, 2, 3, 4, 5]; const arr2 = [6, 7, 8, 9, 10]; function calculateSum(arr) { return arr.reduce((accum, val) => accum + val, 0); } foo = calculateSum(arr1); // Expect foo to equal 15 bar = calculateSum(arr2); ...

NPM Error: Module 'balanced-match' Not Found

After updating the node and npm using nvm, I encountered an error when starting the node server. Despite trying various solutions suggested in stack overflow, none seemed to work for me. Below are the steps I tried: 1. Removed node modules and installed t ...

Utilize jQuery to create a dynamic image swapping and div showing/hiding feature

I'm having trouble implementing a toggle functionality for an image and another div simultaneously. Currently, when the image is clicked, it switches to display the other div, but clicking again does not switch it back. Can someone please advise on wh ...