Reputation: 15750
Folks, Trying to include other .js files to be able to export from a module in the following manner. This will make the main module more readable. I am trying to include code from other functions.
I suppose its not the correct way. Can someone guide me in the right direction?
main module file:
module.exports = {
eval(fs.readFileSync('./extras/foo.js')+'');
fdsa: function (barf, callback) {
},
asdf: function (barf, callback) {
},
}
foo.js:
foo: function (barf, callback) {
...
callback(err, result);
}
Upvotes: 2
Views: 3338
Reputation: 1498
There is a much simple way to achieve this with es6 module pattern. So in foo.js
export function foo(barf, callback) {
...
callback(err, result);
}
And in main.js you will have something like,
export * from './foo.js';
export function fdsa(barf, callback) {
...
}
Upvotes: 0
Reputation: 146004
If you want main.js to basically duplicate and enhance everything foo has (which is silly, but that seems to be what you are asking), you can do this:
main.js
var foo = require('./extras/foo');
for (var prop in foo) {
exports[prop] = foo[prop];
}
exports.fdsa = function(...
exports.asdf = function(...
./extras/foo.js
exports.foo = function(...
Side note if you put a file in somedir/index.js
, it can be required as just somedir
, which can also be useful.
If you just want access to foo
by way of main and are OK with a sub-namespace, just do:
main.js
exports.foo = require('./extras/foo');
Then your calling code can do:
require('./main').foo.foo(blah, callback);
Also note if you want the entire foo
module to be a function, just do:
module.exports = function foo(barf, callback) {...
Upvotes: 7