How to access a static TypeScript variable in Node.js across different files

I encountered a situation like this while working on a node.js project:

code-example.ts

export class CodeExample {
  private static example: string = 'hello';

  public static initialize() {
    CodeExample.example = 'modified';
  }

  public static displayExample() {
    console.log(CodeExample.example);
  }
}

In the beginning, I initialized the CodeExample...

main.ts

import { CodeExample } from './code-example.ts'
...
CodeExample.initialize();
CodeExample.displayExample();  // displays --> 'modified'

Later, when calling a function of a class stored in another file anotherFile.ts

import { CodeExample } from './code-example.ts'
...
someFunction() {
  CodeExample.displayExample();  // shows --> 'hello'
}

Is there a method to make the displayExample() function show 'modified' even on the subsequent call without re-initializing CodeExample?

Appreciate your assistance! Davide

Answer №1

When faced with this scenario, I opt to utilize localStorage since each time we import a class, it is reinitialized.

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

Include personalized headers to the 'request'

I have configured my express server to proxy my API using the following setup: // Proxy api calls app.use('/api', function (req, res) { let url = config.API_HOST + req.url req.pipe(request(url)).pipe(res) }) In this instance, confi ...

Unable to store acquired data into a list upon retrieval with Mongoose

I am utilizing express.js and mongoose to retrieve data from a collection, store it in a list, and then send it to an ejs file. However, I'm facing an issue where the data is not being stored in the list. Here's my code: app.get("/", (req, res) ...

After connecting with passport and mongoose, the issue arises where req.user is not defined

After successfully integrating passport.js with my Next.js application, I have managed to retrieve a user object upon successful login. Exciting! However, I am facing the challenge of making the req.user available in my api/user route. The repository prov ...

The HTML element cannot be set within page.evaluate in Node.js Puppeteer

I've run into an issue while using node.js puppeteer, specifically with the page.evaluate method. I'm experiencing difficulties with this part of my code: console.log(response); //This line is valid as it prints a regular string awa ...

A property in TypeScript with a type that depends on the value of an object

How can we troubleshoot the error not displaying in Typescript and resolve it effectively? Explore Typescript sandbox. enum Animal { BIRD = 'bird', DOG = 'dog', } interface Smth<T extends Animal = Animal> { id: number; a ...

Can you explain Node.js and its applications as well as how it is commonly used?

A while back, during my time at IBM when I was immersed in learning, I came across something known as BlueMix, a cloud product. Within BlueMix, there was a rather primitive component called Node.js. Since that moment, I've been filled with curiosity a ...

Exploring the potential of utilizing functions in express.js to take advantage of the "locals"

Having experience with Rails/Sinatra, I am accustomed to using helper functions in my view files. However, incorporating this functionality into express.js has proven to be quite challenging. You can include locals automatically like this... app.set("nam ...

Cosmic - Ways to incorporate personalized validation strategies into the `getConfigValue()` function?

Why is the getConfigValue() function not retrieving validation values from custom Strategies? For example: @Injectable() export class CustomStrategy extends NbPasswordAuthStrategy { protected defaultOptions: CustomStrategyOptions = CustomStrategyOptio ...

What is the most effective method for pausing execution until a variable is assigned a value?

I need a more efficient method to check if a variable has been set in my Angular application so that I don't have to repeatedly check its status. Currently, I have a ProductService that loads all products into a variable when the user first visits the ...

Creating a JSON-based verification system for a login page

First time seeking help on a programming platform, still a beginner in the field. I'm attempting to create a basic bank login page using a JSON file that stores all usernames and passwords. I have written an if statement to check the JSON file for m ...

Multiple minute delays are causing issues for the Cron server due to the use of setTimeout()

I have an active 'cron' server that is responsible for executing timed commands scheduled in the future. This server is dedicated solely to this task. On my personal laptop, everything runs smoothly and functions are executed on time. However, ...

Test in Node.js with Mocha exceeds its time limit

My Promise-based code is timing out even after all my efforts to fix it. Can someone help me with this issue? export function listCurrentUserPermissions(req, res, next) { return UserPermission.findAll({ where: { ac ...

Transmitting command-line arguments while utilizing node-windows for service creation

Recently, I developed some custom middleware in Node.js for a client that functions well in user space. However, I am now looking to turn it into a service. To achieve this, I utilized node-windows, which has been effective so far. The only issue is that ...

Increasing the token size in the Metaplex Auction House CLI for selling items

Utilizing the Metaplex Auction House CLI (ah-cli) latest version (commit 472973f2437ecd9cd0e730254ecdbd1e8fbbd953 from May 27 12:54:11 2022) has posed a limitation where it only allows the use of --token-size 1 and does not permit the creation of auction s ...

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 ...

Where specifically in the code should I be looking for instances of undefined values?

One method in the codebase product$!: Observable<Product>; getProduct(): void { this.product$ = this.route.params .pipe( switchMap( params => { return this.productServ.getById(params['id']) })) } returns an ...

What causes Bootstrap to malfunction when the route contains double slashes?

When using /something, everything works fine, but when switching to /something/somethingelse, Bootstrap fails to function. It seems that the number of "/" characters in the route is causing this issue, rather than the content inside the .ejs file. Here is ...

Best practices for efficiently utilizing setInterval with multiple HTTP requests in NodeJS

Imagine you have a collection with 3 to 5 URLs. You want to send requests every 5 seconds, one by one. Here is how I approached this: setInterval(() => { array.forEach(element => { request .get(element.url) .on('response', ...

Middleware for cascading in Mongoose, spanning across various levels in the

I have been working on implementing cascading 'remove' middleware with mongoose for a project. In my database structure, I have nested collections as follows: 'modules' -> 'modulesInst' -> 'assignments' -> ...

What's the reason that app.use(app.static(...)); isn't functioning properly?

As someone who is new to programming, I am currently exploring Javascript, node.js, and express. I came across a question regarding the usage of app.use(express.static(path.join(...))); versus app.use(app.static(path.join(...)));. const app = express(); co ...