简体   繁体   中英

Passing a common variable to a module in Node.js

I'd like to create a module in node.js, that includes a couple of functions.
I'd also need a common object for all of the functions to use.
I tried the following syntax, but it doesn't seem to work:

module.exports = function(obj) {
    func1: function(...) {

    },
    func2: function(...) {

    }
}

Where obj is the common object I want the functions to use.

You need to return your functions object:

module.exports = function(obj) {
    return {
        func1: function(...) {

        },
        func2: function(...) {

        }
    };
};

Usage:

var commonObj = { foo: 'bar' };
var myModule = require('./my-module')(commonObj);

module.exports is simply the object that is returned by a require call.

You could just:

var commonObj = require('myObj');

module.exports = {
  func1: function(commonObj) {...},
  func2: function(commonObj) {...}
};

You're trying to use object syntax within a function. So either get your function to return your functions, or just use an object instead and export that. To pass in an argument you'll need something like an init function.

var obj = {

  init: function (name) {
    this.name = name;
    return this;
  },

  func1: function () {
    console.log('Hallo ' + this.name);
    return this;
  },

  func2: function () {
    console.log('Goodbye ' + this.name);
    return this;
  }

};

module.exports = obj;

And then just import it within another file using the init method. Note the use of return this - this allows your methods to be chained.

var variable = require('./getVariable'); // David
var obj = require('./testfile').init(variable);

obj.func1(); // Hallo David
obj.func2(); // Goodbye David

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