I am writing some logic in fileB.js that needs to call another function declared in fileA.js. fileA.js declares a function called abc(). How can I call abc() from fileB.js.
Both fileA and fileB are in the same directory.
Thank you
Ps. I am not using this with HTML. I am just running it locally as part of another project I am working on. I am now using node to run it from terminal. But I am not using anything else in these two files. I just have a bunch of really simple functions. No node.js modules or anything...
Node.js isolates each file as a module, giving each their own local scope to define essentially "private" functions and vars.
With this isolation, fileA will need to export abc in order to share it with other files/modules:
function abc() {
// ...
}
exports.abc = abc;
Then, fileB can require() fileA with a relative path (. referring to the current directory) and use its exported function:
var a = require('./fileA');
a.abc();
If you are using node, then in fileA:
module.exports = { abc: abc } //assuming that abc holds a reference to your function, declared somewhere above
Then, in fileB you require fileA and use what you exported:
var fileA = require('./fileA.js');
fileA.abc();
Since you're running it in NodeJS, I'd suggest doing the following at the top of fileB.js:
var fileA = require( './fileA.js' );
However, in order for this to work, the functions you want to use in fileB.js should be exported from fileA.js. To do this, lets assume that the function abc() is what you want to access:
// In fileA.js:
function abc() {
// ... do something ...
}
module.exports = abc;
If you want multiple functions/variables/objects available to fileB.js, you can export them all as one object:
// In fileA.js
function abc() {
// ... do something here ...
}
var myObject = {
propOne: 'foo',
propTwo: 'bar
};
module.exports = {
abc: abc,
myObject: myObject
};
Then, within fileB.js:
// Import the fileA object you just created.
var fileA = require( './fileA.js' );
// Save references to abc and myObject
var myObject = fileA.myObject,
abc = fileA.abc;
Just include both the JS files in the HTML and then simply call them any function anywhere, it will work.
Related
I'm back again. I had a thought about some code that I would like to split up between multiple files and such. With that, I need an object declared that tracks all stuff, like arrays, counting variables, and that stuff that I need to access and edit across the project.
So, I have a file where I declare all sorts of objects. Let's call this file Constants.js in the tree;
Main.js
Constants.js
Secondary.js
I'm declaring an object in Constants.js, then I'm requiring that object in the main file. After that, I need to run a function where that's in Secondary.js using the global object and edit it in there. The problem is, if I declare it in the secondary file and edit it, it wouldn't be the same (or updated) in the Main.js file, would it?
Ok so, I have my Constants.js file laid out like the following -
// Constants.js
exports.Tools = {
Stack: [],
Test: "foo",
Track: 0
// ...
};
In the Main.js I'm requiring that object using the following code, and editing what's inside it -
// Main.js
const Constants = require("./Constants.js");
const Tools = Constants.Tools;
Tools.Stack.push("Some stuff");
After that, I'd like to run a function, like so -
// Main.js
require("./Secondary.js").run(Tools);
Then after the function has ran, the Tools object needs to be updated what the Secondary.js:run() did to it. For instance -
// Secondary.js
exports.run = function (Tools) {
Tools.Test = "bar";
Tools.Track++;
}
And so, I'd like the object in the main file to be updated with the new values that Secondary.js did to it.
Is there any way possible for this to happen without using functions in that object or maps? I'd like it to be a normal object.
Thank you very much.
~Q
Declare global variable in main file
Main.js
global.Tools = {
Stack: [],
Test: "foo",
Track: 0
// ...
};
In Secondary.js Just use that variables as
global.Tools.Stack.push(value)
In Node.js global objects are available in all modules, It can be used directly,
No need to import any file.
Ok, I have been doing some digging, and the following example works -
// Constants.js
exports.Tools = {
Test: "foo",
Stack: []
};
// Secondary.js
exports.run = function (Tools) {
Tools.Test = "bar";
Tools.Stack.push("Second");
}
And lastly, the main file that gets ran -
// Main.js
const Constants = require("./Constants.js");
const Tools = Constants.Tools;
Tools.Stack.push("First");
require("./Secondary.js").run(Tools);
console.log(Tools);
/*
Outputs:
{
Test: "bar";
Stack: ['First', 'Second']
}
*/
So, the main file's object does get updated when it's passed through the function. It doesn't also matter if you return that object in the Secondary's function.
And also when you do not pass it through a function, it gets ran successfully like so -
// Secondary.js
exports.run = function () {
const Tools = require("./Constants.js").Tools;
Tools.Test = "bar";
Tools.Stack.push("Second");
}
I hope I helped anyone who had this question.
~Q
I have a file that exports one function that relies on a private one:
function __a(filePath, someFunction){
// do some file request
someFunction(filePath)
}
function b(filePath){
__a(filePath, require)
}
module.exports = {
b: b
}
And I'd like to test that the private function __a toHaveBeenCalledWith some parameters so __a does not actually try and fetch some file I can not assure exists.
I understand the concept that when I'm importing b I am getting a reference to the function and __a just lives within the scope of it, and I can't have access to it so using stuff like:
import appResources from './index';
// ... test
jest.spyOn(applicationResources, '__a').mockImplementationOnce(myParams);
How can I avoid __a excecution here and make sure it's been called?
It's impossible to mock or spy on existing function that isn't used as a method.
__a and b should either reside in different modules, or a should be used as a method within same module. For CommonJS modules there's existing exports object that can be used:
exports.__a = function __a(filePath, someFunction){
// do some file request
someFunction(filePath)
}
exports.b = function b(filePath){
exports.__a(filePath, require)
}
Notice that module.exports isn't replaced, otherwise it won't be possible to refer it as exports.
I try to use function from another Javascript file in my Gulpfile, but cannot make it work so far.
The file I need to access in Gulpfile:
var hello = function(){
console.log('Hello')
}
And the way I require it in my Gulpfile:
var tools = require('./public/js/tools.js');
gulp.task('create_subscriptions', function(){
tools.hello();
});
tools.hello() is not a function is triggered.
What do I do wrong here?
Edit
I did
module.exports = {
hello: hello()
};
Whats the difference wit exports.hello = hello?
You didn't export anything from your module. Local variables are not exposed, you need to explicitly mark them as public.
exports.hello = hello;
hello: hello()
You have () after the variable holding the function. You are calling it and assigning the return value (which is not a function) to your hello property.
Is there way to define global variable which will be available inside some module.
So, if we have module test, and inside test we have files index.js, test1.js, test2.js, can we define variable inside index.js to be available in test1.js and test2.js, but not outside this module?
Exact situation:
So, I am using some npm module and I don't want to require that module every time, but only within one directory, not whole node application, because that can cause problems to me.
test1.js:
exports = test1Module = {
func1: function(...){...},
func2: function(...){...},
func3: function(...){ console.log(test1Module.secretVariable); }
}
index.js:
var secretVariable = "secretValue";
var test1 = require('test1');
test1.secretVariable = secretVariable;
And similarly with test2, but NOT test3..
What you are looking for is namespaces.
Take a look at the following
How do I declare a namespace in JavaScript?
var yourNamespace = {
foo: function() {
},
bar: function() {
}
};
...
yourNamespace.foo();
Looking at a random source file of the express framework for NodeJS, there are two lines of the code that I do not understand (these lines of code are typical of almost all NodeJS files).
/**
* Expose `Router` constructor.
*/
exports = module.exports = Router;
and
/**
* Expose HTTP methods.
*/
var methods = exports.methods = require('./methods');
I understand that the first piece of code allows the rest of the functions in the file to be exposed to the NodeJS app, but I don't understand exactly how it works, or what the code in the line means.
What do exports and module.exports actually mean?
I believe the 2nd piece of code allows the functions in the file to access methods, but again, how exactly does it do this.
Basically, what are these magic words: module and exports?
To be more specific:
module is the global scope variable inside a file.
So if you call require("foo") then :
// foo.js
console.log(this === module); // true
It acts in the same way that window acts in the browser.
There is also another global object called global which you can write and read from in any file you want, but that involves mutating global scope and this is EVIL
exports is a variable that lives on module.exports. It's basically what you export when a file is required.
// foo.js
module.exports = 42;
// main.js
console.log(require("foo") === 42); // true
There is a minor problem with exports on it's own. The _global scope context+ and module are not the same. (In the browser the global scope context and window are the same).
// foo.js
var exports = {}; // creates a new local variable called exports, and conflicts with
// living on module.exports
exports = {}; // does the same as above
module.exports = {}; // just works because its the "correct" exports
// bar.js
exports.foo = 42; // this does not create a new exports variable so it just works
Read more about exports
To expand on Raynos's answer...
exports is basically an alias for module.exports - I recommend just not using it. You can expose methods and properties from a module by setting them on module.exports, as follows:
//file 'module1.js'
module.exports.foo = function () { return 'bar' }
module.exports.baz = 5
Then you get access to it in your code:
var module1 = require('module1')
console.log(module1.foo())
console.log(module1.baz)
You can also override module.exports entirely to simply provide a single object upon require:
//glorp.js
module.exports = function () {
this.foo = function () { return 'bar' }
this.baz = 5
return this // need to return `this` object here
}
Now you've got a nice prototype:
var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)
There are myriad other ways to play with module.exports and require. Just remember, require('foo') always returns the same instance even if you call it multiple times.
Note
For the following to work,
var g1 = new require('glorp')()
console.log(g1.foo())
console.log(g1.baz)
this has to be returned in the function that is assigned to module.exports. Otherwise, you'll get a TypeError:
console.log(g1.foo())
^
TypeError: Cannot read property 'foo' of undefined
You can find the best answer in node.js source code.
If someone is requiring your js module,
your script turns into a function by node as follows (see src/node.js).
// require function does this..
(function (exports, require, module, __filename, __dirname) {
... your javascript contents...
});
Node will wrap your script. Then above script will be executed as follows:
//module.js
var args = [self.exports, require, self, filename, dirname];
return compiledWrapper.apply(self.exports, args);
So in your script,
exports is just module.exports.
In your script, you can add something to this exports object (functions..).
require function will return this object. This is node.js's module system (commonJS specification).
But be careful not to modify module.exports. Otherwise your current exports will be meaningless.
module is an object that represents what that particular source file would like to publicly expose. Instead of having something akin to header files in the c/c++ world, you describe what the module exports by defining this object. the node runtime then uses this object to determine what about your module is 'public.'
its a similar concept to exporting functions from a dll in the compiled world. you have to define explicitly what functions can be accessed by the outside world. this helps with encapsulation and lets your organize your libraries in a clean way.
Module's code is wrapped in module.exports (The module, maybe composed by other module).
There are many ways to build a module, but this is one very common (and my personal favorite).
// Dependencies
// const module = require('module');
// Module object
var foo = {}
// Internal property
foo._a = 'a';
// "Public" property
foo.b = 'b';
// Method
foo.fu = function() { return 'fu' };
// Export
module.exports = foo;