Purpose: making a Node.js module or a Requirejs AMD module, from a plain old JavaScript file like this:
var foo = function () {};
I have no control and I can't edit foo.js
.
Whyfoo
is is a plain empty object inside the first if
? How can I "include" a plain JavaScript file in my module? File mymodule.js
:
(function(root) {
if(typeof exports === 'object') { // Node.js
var foo = require('./foo');
console.log(foo); // { }
} else if (typeof define === 'function' && define.amd) { // RequireJS AMD
define(['foo'], function () {
return foo;
});
}
}());
To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.
Explanation: The fsread modules is not a built-in node module in Node. js.
35) Which of the following keyword is used to make properties and methods available outside the module file? Answer: C is the correct option. The exports keyword is used to make properties and methods available outside the module file.
Node modules loaded with require
must populate an exports
object with everything that the module wants to make public. In your case, when you require the file nothing is added to exports
, hence it shows up as empty. So the short answer is that you need to modify the contents of foo.js
somehow. If you can't do it manually, then you need to do it programmatically. Why do you have no control over it?
The easiest being that you programmatically wrap the contents if foo.js
in the code needed to make it a proper module.
// Add an 'exports' line to the end of the module before loading it.
var originalFoo = fs.readFileSync('./foo.js', 'utf8');
fs.writeFileSync('./foo-module.js', originalFoo + "\nexports.foo = foo;");
var foo = require('./foo-module.js');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With