Export modules from node NPM application

I have a node application (which is used as npm fraud and used as a dependency on package.json from another node application) that needs to be granted access to some internal modules (to the application that uses my package as a dependency) all these modules use export for functions that need to be consumed

My "main" module is index.js

inside it I do the following:

var appState = require("./utils/appState"); var appLclStorage = require("./utils/AppLocalStorage"); var processHandler = require("./controller/processHandler"); .... var appApi = module.exports = {}; appApi.appState = appState; appApi.appLclStorage = appLclStorage; appApi.processHandler = processHandler; .... 

I have an add-on module for the outside ...

This works OK , but my question is, is there a better way to do this in node?

+4
source share
1 answer

I find that it works great the way you describe.

You can do a little work by adding the index.js file to the directory and exporting other files from the same directory. Then require directory to get them all.

 // add.js module.exports = function (num1, num2) { return num1 + num2; }; // subtract.js module.exports = function (num1, num2) { return num1 - num2; }; // multiply.js module.exports = function (num1, num2) { return num1 * num2; }; // index.js var Calc = {}; require('fs').readdirSync(__dirname).forEach(function (file) { if (file !== 'index.js') { var fileName = file.replace('.js', ''); Calc[fileName] = require('./' + fileName); } }); module.exports = Calc; // main.js var Calc = require('./calc'); var zero = Calc.subtract(1, 1); var one = Calc.multiply(1, 1); var two = Calc.add(1, 1); 

With the following file structure:

 ├── calc │  ├── add.js │  ├── index.js │  ├── multiply.js │  └── subtract.js └── main.js 
0
source

All Articles