Expressjs - global objects - javascript

I have an app written using express with connections to db, logger and other long living objects that requires to be open and accessed by multiple js files.
What are some of the techniques I could use to make the object "global" with minimal overhead/maintanence?
Thanks

In my opinion, you could put it in a foo.js file and use require('foo.js') to load it. This object is created only one according to This question

Define like this
//global.js
module.export = function(){
//define your global object and function here.
}
and call
require('global.js') in your script where you want

Related

How to use javascript constant in javascript file from another javascript file

I have created one javascript file in which I have declared different string constants.
now in another javascript file I want to use those String constants from already created javascript file.
Is there any way to do this.
Thanks in advance.
If you declare your constants in file1 as global variables:
var someConstant = 42;
Then you can just use that variable in your other JS files. Just make sure file1 is loaded before you try to use them.
However, polluting the global scope like this come with it's risks, as those variables are easily changed.
Multiple ways.
Concatenate
Use a task runner like grunt to define a task that concatenates your files into a single one. This will not only allow convenient definition of constants but also improve performance.
There are other tools to do this, too. See Prepros for windows and codekit for Macs.
Modularize
If you are on client side, use a tool like require.js or browserify to define commonJS / AMD modules and require them as you need.
If you are on server side using node, this works out of the box for commonJS.
Load scripts in correct order, expose them through global objects.
You could load your constant defining script first and do something like this:
var constants = {
MY_CONST: 'Foo'
}
Your main, whi script could access this variable. If you omit the var keyword, the variable becomes globally available. Note however that this should be avoided.
You could even add a property to the global object (window on the client side).
Personally I like to use commonJS modules when working on projects that allow me to do so. Rob Ashton has an opinion on this that I would like to share.
When I can't use those modules in a convenient way, which would be the case when working with (custom) web-components because of their isolated scopes, I like to add a single script which creates
an Object like App. I use this object to expose modules, services & constants which can then be required by any component in a neat way:
App.myService.doSomething()
Create a file which contains all the constants and variables
Constants.js
const EMAIL = "xyz#gmail.com"
const PHONE = "9911223344"
var NAME = "Default name"
Access the Constants.js file in your HTML file
xyz.html
<script src="Constants.js"></script>
Now you can access the Constants in any of file inside a project

Javascript global declaration

I've just started out with javascript and came across this line in a file called global.js There is only one line in the file. I'm not sure what does App do. Any ideas?
Filename: globals.js
//The Application
App = {};
it creates an object with a name of App... that's all it does.
I would assume that the idea behind the global.js file in your case is to include the file in your base html/template so that the variables in there can be accessed from anywhere in the app.
In some of our projects, we've had global files like this containing references to collections and "setting" variables, which is quite handy :)
It is creating an object named App in the global namespace. App has no functions or attributes (yet).
It (implicitly) declares a variable called App in a "global" context and assigns an empty object as its value. Assuming this is used on a web page somewhere, it's the same as declaring window.App = {}.
How this affects the rest of your application, we won't know until you post more relevant code.
This script just instantiate this empty Object. Probably, others scripts that ran along with this uses that object and depends that it is created there.

Extend JavaScript Class from separate file

I'm sorry to ask quite a dim question as I'm very new to OOP in JavaScript.
I'm trying to use John Resig's Simple JavaScript Inheritance method, and ideally I'd like to store this within say utils.js, and then use it (using Class.extend), throughout the range of script files that my project uses. Is this possible? I've noticed that if I create a subclass from within my utils.js file, I can then create a new instance of that class from a different script, so that makes me think it might be possible. Does it have something to do with the method being wrapped in an immediately-invoked function expression?
Sure it's possible, just load the util.js file before the rest. ALthough if I were you (seems like you're starting to have several different files in your project) I'd check out http://requirejs.org/ or some other AMD library to break up your project in modules.
Yes, this is possible only thing is you have to include Utils.js file before calling Class.extend, so that browser should be able to find the base class.
Browser works like an interpreter, it loads scripts once it finds the script tag
Does it have something to do with the method being wrapped in an immediately-invoked function expression?
Yes, in the moment in which the utils.js script is loaded, the method executes and returns the object Class to the global scope. From then on, the object can be used in all other files.

Creating a "controller" script for Node.js

I'm creating a program in Node.js. I'm pretty new to programming anything other than small javascript functions for websites so please bear with me if my terminology/ideas are totally wrong.
I originally had the entire program in one giant (~500 line) script file. Several people suggested I split it up into separate classes, where each class only has one 'job' to complete. I like this idea as it has helped me really streamline my code and make it more modular and manageable.
My issue is: How do I access these classes from a central file?
For instance, pretend I have 3 classes, in 3 separate javascript files, all containing 3 functions each. I want to access and pass data to/from all of these from one central "controller" script. What's the best way to do this? Can I just require it into a variable, then access the script's functions like so?
var class1 = require('./class1.js');
class1.function1(); // call the first function contained in class1.js
Is such a thing even possible? Again, totally new to this.
NodeJS supports CommonJS modules. A CommonJS module provides three global variables: module, exports and require.
You can export your API by adding to the exports object and require these files just like other node modules (add ./ to indicate that it is relative to the current file), assign it to a variable and access the values you added to that files exports object:
// first-module.js
exports.hello = 'world';
exports.num = 23;
// main.js
var first = require('./first-module');
console.log(first.hello);
console.log(first.num);
You need to add functions to the exports object in class1.js.
require("./class1") will return this object.

How to manage multiple JS files server-side with Node.js

I'm working on a project with Node.js and the server-side code is becoming large enough that I would like to split it off into multiple files. It appears this has been done client-side for ages, development is done by inserting a script tag for each file and only for distribution is something like "Make" used to put everything together. I realize there's no point in concatting all the server-side code so I'm not asking how to do that. The closest thing I can find to use is require(), however it doesn't behave quite like script does in the browser in that require'd files do not share a common namespace.
Looking at some older Node.js projects, like Shooter, it appears this was once not the case, that or I'm missing something really simple in my code. My require'd files cannot access the global calling namespace at compile time nor run time. Is there any simple way around this or are we forced to make all our require'd JS files completely autonomous from the calling scope?
You do not want a common namespace because globals are evil. In node we define modules
// someThings.js
(function() {
var someThings = ...;
...
module.exports.getSomeThings = function() {
return someThings();
}
}());
// main.js
var things = require("someThings");
...
doSomething(things.getSomeThings());
You define a module and then expose a public API for your module by writing to exports.
The best way to handle this is dependency injection. Your module exposes an init function and you pass an object hash of dependencies into your module.
If you really insist on accessing global scope then you can access that through global. Every file can write and read to the global object. Again you do not want to use globals.
re #Raynos answer, if the module file is next to the file that includes it, it should be
var things = require("./someThings");
If the module is published on, and installed through, npm, or explicitly put into the ./node_modules/ folder, then the
var things = require("someThings");
is correct.

Categories

Resources