Difference between storing in app.locals vs global object - javascript

I saw some people use app.locals to store properties that is available across all views.
Also other people used global.AnyNameVariable to store anything even like requiring config.js files and etc
ex:
app.locals.objOne = {
name:'John'
}
global.objTwo = {
name:'Doe'
}
What is the difference between them? and what is the purpose? what is the right way to use both?

As the documentation states,
The app.locals object has properties that are local variables within the application.
This is application-level container provided by the framework that serves to store application settings, etc. There can be more than one Express application, while global is global.
app.locals is available as req.app.locals within middlewares, this way it can be decoupled from specific app variable.

Related

What's the best way to wrap Redux's API so that store instances are transient instead of singletons?

I haven't had a look at the source in-depth or anything yet, but was just curious if anyone has required or made use of this in the past or not.
It appears as though Redux is creating a singleton instance for the store and persisting this for the lifetime of the caller, but this is not really tenable for what we're thinking of implementing... what is the simplest approach, if one exists, for extending their API and creating stores with scoped lifetimes?
This is in the context of Redux being used in a purely server-side application (or at least as far as it can tell etc.)
Edit:
Similarly, while you can reference your store instance by importing it
directly, this is not a recommended pattern in Redux. If you create a
store instance and export it from a module, it will become a
singleton. This means it will be harder to isolate a Redux app as
a component of a larger app, if this is ever necessary, or to
enable server rendering, because on the server you want to create
separate store instances for every request.
I found this excerpt in their documentation here.
How does this module exporting consideration work in practice? If I only access the store within the scope I declared it for a given lifetime via externally exposed methods, should I expect the instance to be deallocated when the scope closes in some specified app lifetime?

Adding keys to express instance good practice?

In the case where I would like to share some information from my index.js file to multiple endpoints in different routes, would simply sticking a custom key to the express instance (app) be fine? For example, lets say I'm using socket.io and would like multiple endpoints emitting from the instance I created, would just saying app.socketIo = io be fine? Is there a better way of doing this if this is not the case?
app.set() and app.get() are designed for this purpose, though some named parameters are reserved for special use.
There is also app.locals which a shared object that is entirely your own namespace, no conflicts at all.
While you could apply your own properties to the app object directly, that runs a risk of conflict with future development of Express and would generally not be recommended for that reason. I'd suggest using app.locals which is conflict-free and entirely for your own use.
Values in app.locals values are also available to templates using the Express template interface so that's where you can set application-level variables that are available to all templates (such as an application name).

Node.js: How does process.env differ from global?

How is setting an environment variable like process.env.thing = 42 different from creating a global variable like global.thing = 42?
When would prefer process.env.thing over global? What are the pros/cons of both objects?
global is the global object. process is available globally, because it is a property of global. In fact:
global.process === process //-> true
process.env has properties set to the environment variables of the system. These can be set a variety of ways outside of node itself, and read in by accessing properties of process.env.
At the command line try:
FOO=bar node -e "process.env.FOO"
The process module is just a globally available thing.
The choice in my opinion must be something like this.
1)If the variable depends on the environment it must be set in process.env
2)If the variable is just a constant that is accessible from the entire application it must be set to global.
I think if you don't face these 2 points you don't have a need to store some value in both
If you start your node.js application you may want to use some different "environments", like API-URLs and stuff like this, because in a production / live environment those URLs are usually different in comparision to your local development environment.
This means that you can inject those paths using a .env file for example BEFORE starting your application.
This is an example:
NODE_API_URL=https://myApi.com/myEndpoints myApp.js
The global.thing = bla line will be read after the environment variables were set.
Once the application is running the environment variables and the other global definitions can be accessed by the app.
from the docs NodeAPI
The process object is a global that provides information about, and
control over, the current Node.js process. As a global, it is always
available to Node.js applications without using require().
You want to attach your environment variables to this object to make sure that there is no other pollution of globals.

Globally available variables with Angular

We are in the process of migrating our webapp to Angular.js. Traditionally, we created a global object named app and used it to store functions, variables, etc. that were used globally. For example, the active user's name and avatar might be stored in app.user.
With the transition to angular, app is no longer just an object, it is an angular app module. What is the correct way to store data globally like this in an Angular mindset? It could be completely different, that's fine. I just want to make sure we do it correctly.
I would do something as simple as app.global = {}; and use app.global around the site, but if the angular API ever changes to use a property named global, it would be a nightmare to fix.
Angular is fairly allergic to global variables. I would recommend using a service (e.g. UserDataService) to hold this data and injecting it where it is needed (like in a controller).
Your service will be a singleton that can be accessed wherever it is injected.
The correct way to do this would be to provide the value or function to angular's dependency injector via Module.value or Module.constant. See: http://docs.angularjs.org/api/angular.Module
Well, you can also set it in rootScope as:
var app = angular.module('appName'){
//other codes removed
});
app.run(function ($rootScope) {
    $rootScope.globalVariable = 'hello'; //global variable
});
Now you can access the globalVariable

Nodejs global variables and modules

Are there any security issuses or something with using global variables and assignig modules to global variables in nodejs?
example:
client = new Client();
Without the var statement, so i can use it everywhere?
It's not that it's a security problem, it's considered bad practice though and it can lead to other problems such as trying to override a Node.js global variable.
Try not to pollute the global namespace and if you really really need global variables, just use one with sub-objects.
I don't think there are security issues per se, but you will be polluting the global namespace. As your project grows (especially with more than one programmer) the risk of conflicts gets bigger. And what if you later on add a third party library to your project that has a variable named 'client'?
I've been using Node for a couple of years and I had the same "problem" you have and is frustrating. Nevertheless I can give you the solution I reached and it works for me.
Node doesn't allows global variables in the way you ask since variables defined as global in a module are global only for that module. But exists a GLOBAL object that ban be used for what you need.
Global variables are a bad idea in general (always), but having a global cache of useful functions in it's own namespace is not a crime at all since it will not override anything and lets you use it along your code. So I'll tell you what I do to share functions and objects between modules and keep source organized (that's important for me at least!):
1st Create a resource file where you place all important functions and objects you want to share across your code. I call mine "R.js", R from Resources
2st Define the "R" object that will store all functions and objects and assign it to node's GLOBAL object:
var R = {};
GLOBAL.R = R; // Adds resource module to global
3rd For sake of simplicity and avoid extra requires all arround the code, I do all needed requires inside R.js. After that you only need to use them with R.require_variable.function_or_property
// All needed requires
R.fs = require('fs');
R.net = require('net');
R.http = require('http');
R.dbClient = require('mysql').Client;
...
4th Create the shared functions, variables and objects you like inside the R object
5th Where needed arround your code, require the R.js file and access to it's member by using the R object
R.<property_or_function>
2 warning notes.
Remember to always call shared functions or user shared objects placind "R." in front of it
Althought you can assign new functions, objects and properties to R object anywhere this can lead to the same inconsistencies you would have with global variables if you don't plan it in advance - i.e. you call a shared function before assigning it to R - so as a methodology, create everything in the R.js file instead of doing it all arround your code. This way all shared things will be in R.js and that is the only place to look for shared code.

Categories

Resources