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);
}
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);
}
Share
Improve this question
asked Mar 2, 2014 at 0:00
CmagCmag
15.8k26 gold badges97 silver badges147 bronze badges
3
- 1 Just make foo.js a module that exports functions. Then in main file var foo = require('./extras/foo'); – bryanmac Commented Mar 2, 2014 at 0:05
- 1 nodejs/api/modules.html – bryanmac Commented Mar 2, 2014 at 0:06
- so if other functions call the main.js, how would they use the submodule of main called foo? – Cmag Commented Mar 2, 2014 at 0:07
2 Answers
Reset to default 7If 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) {...
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) {
...
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745290678a4620838.html
评论列表(0条)