I can't find anywhere to tell me that this is completely wrong so here I go:
In my module I have two functions:
init: create the winston logger object
get: returns the object
I have several files which need to use the logger object.
In these files, I'm requiring the module, and using the get function.
I want to initialize it once. Then in other files, I want to simply require the module, get the object, and use it. Is my logic completely wrong here? I can pass it to the other modules, but I thought this would be a clean way of using the logger.
Currently in the file where I init and get the logger, I can use it just fine. Once I'm in a new file/module, the get returns undefined which leads me to believe this is incorrect.
Related
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.
It seems that in Node.js 'require' and 'module.require' are not only separate objects but also different types of objects. 'require.resolve' exists but 'module.require.resolve' does not.
Is there any way to call resolve on module.require?
The reason I would like to do that is I would like to call require.main.require.resolve() to see what require.main.require
resolves a given path to.
Here's what I can find out to explain.
require.main gets you the module object for the script that was run first in this node.js process.
require.main.require gets you a function you could use to load scripts as if you were in that main script.
require.main.require does not have a .resolve() method. While require.main.require does get you a require function, as you have found it is not the exact same object that you get when you are in a module itself. It is just a function and appears to have none of the properties that the require object has in your own module.
The require object in your own module gets created by a special function called makeRequireFunction() in the loader (see source code here). That's where the other properties are added to it. But, the require.main.require is the same as process.mainModule and is just the require function by itself, not that special object.
A work-around would be to export resolve() from your entry script then access that exported function from the other script.
In your main module, you could put this:
module.exports.resolve = require.resolve;
Then, you could access that elsewhere with:
require.main.exports.resolve(...);
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
I'm refactoring a large javascript codebase to use RequireJS. Unfortunately, many of the files I'm dealing with are not object-oriented, and cannot return an object without significant modification. Is there a more efficient way to give 'dependent' modules access to the functions and variables contained in a module (without returning an object) ?
I have read about using the exports syntax for defining modules, but it is very unclear whether that would be a valid solution for this situation.
In a defined module, the exports object is what gets exported from the module and passed to whatever module requires it.
Consider this:
define(["exports"], function(exports){
exports.myCustomFunction = function(){};
exports.myCustomObject = {};
exports.myCustomVariable = true;
})
This module will place all the disparate functions and/or objects that you want made public onto the exports object.
At this point RequireJS will use that exports object to pass to a module that requires it:
require(["nameOfCustomModule|filename"], function(myCustomModule){
//evaluates to true
console.log(myCustomModule.myCustomVariable);
})
Here's a simple fiddle. Just bring up your console and you will see the value logged there. http://jsfiddle.net/xeucv/
Hope this clears it up a bit!
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.