Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exporting Objects with the Exports Object

Tags:

Say I have one .js file containing a javascript object. I want to be able to access that object and all of its functionality from another .js file in the same directory. Can I simply export this object with the module.exports object and require() it in the other .js file? If this is possible can you give me an example?

If it helps I'm developing with node.

like image 784
Connor Black Avatar asked Sep 18 '12 02:09

Connor Black


2 Answers

This is the way I create modules:

myModule.js

var MyObject = function() {      // This is private because it is not being return     var _privateFunction = function(param1, param2) {         ...         return;     }      var function1 = function(param1, callback) {         ...         callback(err, results);         }      var function2 = function(param1, param2, callback) {         ...         callback(err, results);         }      return {         function1: function1        ,function2: function2     } }();  module.exports = MyObject; 

And to use this module in another JS file, you can simply use require and use your object as normal:

someFile.js

var myObject = require('myModule');  myObject.function1(param1, function(err, result) {      ... }); 
like image 166
c0deNinja Avatar answered Sep 30 '22 12:09

c0deNinja


Of course you can. In my example I use obj to hold my config info. I put it in a file called index.js in config folder. This makes the index the preferred choice to be picked when I import 'config'. I have 2 exports here one for my node and api stuff and the other for my db. You can ignore the first bit where I set the environment.

const environment = {   development: {     isProduction: false   },   production: {     isProduction: true   } }[ process.env.NODE_ENV || 'development' ];  export default Object.assign({   host: 'localhost',   port: '3000',   remoteApi: {     token: {       'X-Token': '222222222222222222'     },     base: 'https://www.somedomain.com/api'   } }, environment);  export const db = {   dbHost: 'localhost',   dbPort: 176178 }; 

Calling import config from '../config'; will pick the default one. And if I specify I can get the db export import { db } from '../config';

like image 22
Vahid PG Avatar answered Sep 30 '22 12:09

Vahid PG