How to access global variables in node.js modules?

I'm looking to move some functionality to a new file called helpers.js. Below is the code that I have put in this file. How can I access the app variable within my method so that I can retrieve the config element called Path?

Helpers = {
    fs: require('fs'),
    
    loadFileAsString: function(file) {
        return this.fs.readFileSync(app.set('Path') + file) + '';
    }
}

module.exports = Helpers;

Answer №1

Upon review, it seems that you are in need of the app variable from Express. One option is to pass it as a parameter to the function loadFileAsString:

helpers.js

Helpers = {

    ...

    loadFileAsString: function(file, app) {
        return this.fs.readFileSync( app.set('Path') + file)+ '';
    }
}

module.exports = Helpers;

some_file.js

app = express.createServer();
...
helpers = require('./helpers.js');
helpers.loadfileAsString(file, app);

If you prefer to make the app variable global, you can achieve that by using global.app = app. This way, you can access the app variable from anywhere without needing to pass it as a function 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

Algorithm for Filling Tiles in a Gaming Environment

Background: In my current project, I'm developing a unique tile-based game in Javascript. The game involves a character who can freely move around the map without taking diagonal paths - only left, right, up, or down movements are allowed. As the cha ...

Is it possible to ensure only one value is set as true in useReducer without manually setting the rest to false

I am seeking a more efficient method to ensure that only one value is set to true while setting the rest to false I came across this Python question and answer recommending an enum (I am not very familiar with that concept) Currently, I have the followin ...

The JSON output is not displaying correctly

I've been attempting to utilize JSON.stringify in order to format my json object for better readability. However, it doesn't seem to be working as expected. Can someone please offer assistance in identifying what I might have done incorrectly? ...

Create a continuous integration pipeline utilizing Azure DevOps platform

During my attempt to create a React application, I encountered an error while building the Azure pipeline using Azure DevOps. View the error image from the Azure pipeline in Azure DevOps The code for the azure-pipeline.yml file can be found in my GitHub ...

Revamp the component onclick functionality in ReactJS

Within my component, I have an onClick method defined. This method makes a call to the backend and fetches some data. However, the values retrieved from this call are only reflected after refreshing the browser. Is there a way to re-render my component wit ...

The wrap() method in jQuery clones elements multiple times

I have created a simple function that wraps a div tag inside another div tag when the browser window exceeds a certain width of x pixels. However, I've encountered a strange bug when resizing the page more than once. Let me share with you the jQuery ...

Yarn encountered an exit code of 1 and failed to create the app during the command execution

I've been working on creating a next.js app with tailwindcss, but I keep encountering an error when using the following command: yarn create next-app -e -tailwindcss demo-app-full Every time I run this command, it gives me the following error message ...

Use Node.js with Selenium and WebdriverIO to simulate the ENTER keypress action on

I have put in a lot of effort trying to find the solution before resorting to asking this question, but unfortunately I have not been successful. All I need to know is how to send special characters (such as the enter key and backspace) with Node.js using ...

The Angular2 view is failing to display updated data from a shared service

I've been struggling to show data from my shared service, but it's not displaying. Can someone please help me out? I've been stuck on this for the past few days. I've tried NgZone and ChangeDetectorRef, but they haven't worked for ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

Vue error: Uncaught promise rejection - RangeError: The computed value update has exceeded the maximum call stack size

My computed code snippet: computed: { display: { get() { return this.display }, set(newValue) { this.display = newValue } } }, Attempting to update the computed value from a function in ...

What is a way to nest a promise request within another request?

Q: How can I create a new promise within a request, and then return it in a nested request? Here is the code snippet: request({ // --------------request 1------------ url: request_data.url, method: request_data.method, form: request_data.data ...

A guide to placing tooltips dynamically in highcharts column charts

I am encountering an issue with tooltips in Highcharts column charts. The problem arises when the series fill up my chart, causing the tooltip to be hidden below the series and cut off by the end of the div. You can see an example here: https://i.stack.i ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

Leveraging the power of AJAX with either jquery or plain javascript to parse nested JSON data and display the

Similar Question: jquery reading nested json I am seeking a reliable method to iterate through multiple sets of data stored in JSON, some of which may have deep levels of nesting. My goal is to display this data in a table format. I am uncertain abou ...

Using formidable to parse form data in Node.js

Hello everyone, I'm a beginner with node.js and I'm currently working on setting up a file/image upload script. After successfully installing node on my VPS, I came across this helpful guide that assisted me in setting up the app with formidable ...

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...

JavaScript struggles when dealing with dynamically loaded tables

I am currently working on integrating the javascript widget from addtocalendar.com into my website. The code example provided by them is displayed below. Everything functions as expected when I place it on a regular page. However, I am facing an issue wher ...

What is the reason behind "npm update" only updating the module(s) and not its SemVer in package.json?

My "package.json" file shows an old version of the express module - "4.10.0" https://i.stack.imgur.com/xyEDz.png The command "npm outdated" suggests updating to version "4.17.1" https://i.stack.imgur.com/rmqWJ.png Even after running "npm update" to ver ...

Is it possible to utilize a CSV file to dictate which images should be utilized on my website as a guide?

I'm currently working on my website's gallery and have a collection of over 60 images. I'm exploring ways to streamline the process of displaying these images by having the website read their names from a CSV file instead of manually coding ...