简体   繁体   中英

NodeJS module.exports submodule

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);
}

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) {...

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) {
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM