0

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.

3 Answers 3

3

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

I want to initialize that object from another file (server.js) after I get that object from a different module. Any ideas?
I'm not sure what you mean, sorry. You want server.js required and run it's init() from these functions?
The object that I need to be available in that module is created in another file. Only after it has been created I want to pass it to the module. Was that clear enough? sorry for that
So you want to import a file after that file has been created? Sounds like a bad pattern to depend on something not yet existent.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.