2

Simple example:

file1

module.exports.foo = function(obj) {
  module.exports.obj = obj;
}

file2

file1 = require("file1")
var something = {a: "a"};
file1.foo(something); //export "something" being a part of file2

The example above is not working.

What I want is basically a module.exports helper, since I plan a few helpers for whole object "exportion".

Thank you

4
  • What error, you are getting ? Commented Oct 1, 2012 at 12:11
  • 1
    The code you have posted works exactly as you seem to expect. Test case: var f2 = require('./file2'); var f1 = require('./file1'); console.log(f1.obj); outputs { a: 'a' }. Commented Oct 1, 2012 at 12:13
  • When I try to access the "file2" module from a third file, the "file2" module is empty. I want to export objects from file2, but the act of export is happning in a function inside file1. Commented Oct 1, 2012 at 12:27
  • Why don't you just return obj; in the foo function? Commented Oct 1, 2012 at 14:06

1 Answer 1

1

module in file1.js is a different instance from that in file2.js.

file1.js

module.exports.foo = function(obj) {
    module.exports.obj = obj; 
    return module;
}  

file2.js

console.log("running file2");

file1 = require("./file1");

var something = {a: "a"}; 
var moduleOfFile1 = file1.foo(something); //export "something" being a part of file2 

console.log("file1 module: " + moduleOfFile1.id);
console.log("file2 module: " + module.id);

console:

node file2.js

id returned are different


Update

alternatively, why not update file2.js to extend its module.exports

File2.js

// well, you may copy `extend` implementation if you 
// do not want to depend on `underscore.js`
var _ = require("underscore");     
file1 = require("./file1");  

_.extend(module.exports, file1);

var something = {a: "a"};  
// or do something else

_.extend(module.exports, {
    obj: something
});

File3.js

file2 = require("./file2.js");
console.log(file2.obj.a);
Sign up to request clarification or add additional context in comments.

2 Comments

Another question: why is "this" an empty object outside a function? I though the "module.exports" would belong to "this".
This may help you understand the confusing this in JavaScript. In summary, the value of this depends on where it's accessed.

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.