简体   繁体   中英

Expose modules from node NPM application

I've node application (which used as an npm moudule and used as dependency on the package.json by other node app) which need to provide access to some internal modules (to the app which is using my package as dependency) all those modules use export for the functions which needed to be consume

My "main" module is the 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've additional module to expose outside...

This is working OK but my question is whether there is a better/cleaner way to do that in node?

I find it works fine doing it the way you describe.

You could build on it a little by adding an index.js file in a directory and having it export the other files from the same directory. Then require the 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

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