Making modules global for use in other files in node.js - node.js

I read in another question that i can not find now that it was a bad idea to make modules in node.js global, then he changed his answer because of changes in node.js
The examples for express.js on github does now show an example.
https://github.com/visionmedia/express/tree/master/examples
So what if i need the same module in multiple files, like sequelize or async?
app.js:
var document = require('./routes/document')
async = require('async');
/routes/document.js:
async.series([...]);
OR
app.js:
var document = require('./routes/document')
var async = require('async');
/routes/document.js:
var async = require('async');
async.series([...]);
Should i require the async module again in document.js, or just make async global so that i can use it without require it in new files?

Do not use globals to access modules. Always use require and only require() the modules you need in that .js file. Require will only load your module once and hold a reference to it.
Only requiring what you need, even if it's several modules, is good because it makes it clear what the dependencies of your code are and might help you restructure your code later.
Only requiring() what you need can also help at the point where you want to replace one module with another. For example, you might want to replace knox(S3) with the new aws-sdk module. When you remove the knox npm module, require will immediately blow up in the files that use/require knox. If it was a global variable, you would need to find all references to that global reference and rely on your IDE or text editor to find it.

In short, include it in each file. The file is cached after the first require, so the content is really only run once (you can test this by putting a log statement in the require; it'll only show once).
What I do is make one file which requires all the others I need, and exports them all. Then you only need to require the one file. This can be really handy when you have many modules that you're including.

There is nothing wrong with requiring a module more than once. Internally require only executes the required file once and then caches the result. See the Node.js Modules documentation for more information.

Related

No code suggestions for global defined variables in VSCode in a node.js server project

I have to deal with a node.js server project that uses global variables for common APIs. For instance in the entry point server.js there is a Firebase variable for the real-time database that is stored like this:
fireDB = admin.database();
I wasn't aware that this is possible and I would consider this a bad approach, but now I have to deal with it.
I'm not really interested to re-write any of the many calls to this variable in all those files, rather I would find a way to make fireDB show me suggestions only by changing this variable or installing an extension.
I tried to define it on top of the file as var fireDB, but then suggestions only work in the same file, not in others.
When I set a dot behind admin.database() the suggestions work, when I write fireDB. I get no suggestions, yet the call seems to be possible. Suggestions need to work in other files, too. How can I get this to work?
WARNING: MAKE SURE YOU UNDERSTAND THE PROBLEMS WITH GLOBALS BEFORE USING THEM IN A PROJECT
The above warning/disclaimer is mostly for anyone starting a new project that might happen across this answer.
With that out of the way, create a new .d.ts file and put it somewhere with a descriptive name. For example, globals.d.ts at the top level of the directory. Then just populate it with the following (I don't have any experience with firebase, so I had to make some assumptions about which module you're using, etc.):
globals.d.ts
import { database } from "firebase-admin";
declare global {
var fireDB: database.Database;
}
IntelliSense should then recognize fireDB as a global of the appropriate type in the rest of your JavaScript project.
Why does this work? IntelliSense uses TypeScript even if you're working with a JS project. Many popular JS packages includes a .d.ts file where typings are declared, which allows IntelliSense to suggest something useful when you type require('firebase-admin').database(), for example.
IntelliSense will also automatically create typings internally when you do something "obvious", e.g. with literals:
const MY_OBJ = { a: 1, b: "hello"};
MY_OBJ. // IntelliSense can already autocomplete properties "a" and "b" here
Global autocompletion isn't one of those "obvious" things, however, probably because of all the problems with global variables. I'd also guess it'd be difficult to efficiently know what order your files will run in (and hence when a global might be declared). Thus, you need to explicitly declare your global typings.
If you're interested in further augmenting the capabilities of IntelliSense within your JS project, you can also use comments to explicitly create typings:
/**
* #param {String[]} arrayOfStrings
*/
function asAnExample(arrayOfStrings) {
arrayOfStrings. // IntelliSense recognizes this as an array and will provide suggestions for it
}
See this TypeScript JSDoc reference for more on that.

Is there a way to use functions from a "double require"

Sorry if the title is misleading or vague, I couldn't really think of a good way to describe what I'm trying to do.
Basically, I have my index.js file calling another file via a require, we'll say it's js_functions.js.
js_functions.js is calling multiple files via require, and those individual files are all exporting functions correctly.
For sake of example, we'll say that the structure is index.js > js_functions.js > add.js.
Is there a way to call a function from add.js in index.js without directly requiring the add.js in index.js (via js_functions.js)?
If index.js wants to call a function from add.js, then you have two options:
index.js can require('add.js') directly and thus get the exported function from add.js to call.
js_functions.js can export the function from add.js so when you require('js_functions.js'), the function you want to call from add.js is available in the js_functions.js exports.
Generally, I avoid dual exporting as in option #2 and if I want a function from add.js, I just make the dependencies direct and clear require('add.js') so I can get access to that function.
If you're new to node.js module development, then it takes a little getting used to that you start every new module definition, but just adding all the require statements that you need to get access to the modules/functions you need. But, this is how you do module development in node.js and it has all sorts of benefits (testability, resuability, sharability, clear dependencies with no implicit dependencies, etc...). So, just get use to adding a little extra code at the start of each module to import the things you need.
Is there a way to call a function from add.js in index.js without directly requiring the add.js in index.js (via js_functions.js)?
Only if js_functions.js exports the function from add.js that you want to call. Just because js_functions.js has already done require('add.js') that does not provide access to the exports in add.js to any other code besides js_functions.js.
In the future, we can help you more accurately and quicker when you include the actual relevant code. We tend to do a lot better with specific questions that contain specific code than theoretical questions that try to use words (and no code) to describe some problem.

Object doesn't seem to load with all of its properties. - Node.js

I have two js files on my node server that require each other.
both have objects that are exposed via the module.exports mechanism.
1st file is located under bl/commands.js and uses:
var smUtil = require('./../utils/smUtil');
2nd file is located under utils/smUtil.js and uses:
var commands = require('./../bl/commands');
When a function runs from smUtil.js and uses some properties of commands.js it seems like command is an empty object and the import was not successful.
Here is the catch, when i remove the require of smUtil form inside commands.js everything works, which makes me think that i'm doing a newbe mistake.
Any thoughts?
Node.js documentation about circular dependencies
You are absolutely right that empty objects are returned.
To Quote Node.js documentation
When main.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop, an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.
A solution could be to create a separate file to require both the files there and instantiate that file to avoid the circular dependency.
The specific solution which solved my problem was to place var smUtil = require('./../utils/smUtil'); Underneath the module.exports inside commands.js.
However i feel like this solution is not the best one out there.
Thanks to the author of:
coderwall.com/p/myzvmg/circular-dependencies-in-node-js

Require a file within itself in node.js

How do you require a file within itself in node.js? E.g. api.js:
var api = require(./api.js);
What is the best practice for doing this?
You can totally do it. Try this, for instance (in a file named a.js):
exports.foo = 'foo';
var a = require('./a');
console.log(a);
exports.bar = 'bar';
console.log(a);
At the point where require executes, it will return the module a as it exists at the point where require runs so the field foo will be defined but not bar.
There's no point to doing this though. You use require to bring into your current scope an object which would otherwise not be available (namely, a module). But you don't need to do this to access the module you are currently in: it is already fully available.
The code above works because Node has rules to handle cyclic dependencies. And here you have a module which is cyclicly dependent on itself. Rather than go into an infinite loop of requires, Node has require return the module as built up to that point: a partial module. And the modules in a cyclic dependency have to be designed to handle the fact that they may get partial modules.
Cyclic dependencies are to be avoided as much as possible. Most of the time this means refactoring the modules to avoid the mutual dependency by moving functionality into one or more new modules.
So, again, the best practice is to not do this in the first place.

node.js setting a global variable

I'm new to node js. I searched a lot on stack overflow on this question below, none what I need.
I have an app.js file which initiates node server and a router file. I want to be able to store a global value once and shared across other server side .js files which contains my functions. I also want this variable to be accessible in my .jade file. (I use express BTW)
Is there a way to accomplish this?
Thanks.
The Node.js documentation says under Module Caching
Caching Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will
get exactly the same object returned, if it would resolve to the same
file.
Multiple calls to require('foo') may not cause the module code to be
executed multiple times. This is an important feature. With it,
"partially done" objects can be returned, thus allowing transitive
dependencies to be loaded even when they would cause cycles.
If you want to have a module execute code multiple times, then export
a function, and call that function.
Which means you can easily expose a global object simply by putting it in its own module.
//config.js
var config = {
dbUrl: 'mogodb://localhost:2107/persons'
};
module.exports = config;
And then when you want to gain access to that object, you simply do:
var config = require('./config');
And that's done, you get access to the same instance everywhere.
You'll want to limit the usage of global vars in Node. This is because unlike any other server side language, Node is a persistent process that share all request. So you cannot setup user state globally as those will be shared across all user accessing your site.
In raw node, there's two global context:
global.foo = 'bar';
// and the process object
process.some_var = 1;
In Express, you can setup application wide vars using app.set
But, most of the time you'll want to share data by adding them to the request or the response objects. That is because those objects are "user" specifics, unlike the global namespace.
For the template, you'll always want to pass in the context:
app.render('email', Object.assign( aSharedObject, {
specific: 'values'
}));
i would use process.env or if you are using nconf put it into the app configuration as Jordan said, globals are BAD idea, also if you don't want to include nconf or any other conf module or use process.env then you can create a module and export a set of getters and setters to handle the value

Resources