Payne Chu
Payne Chu

Reputation: 573

coffeescript node.js mutually require return undefined

how can I implement something like this in coffee script? when I run node a.js both A and B is type function

a.js

exports = module.exports = A;
var B = require('./b');
function A() {
  console.log('I\'m A');
}
console.log('B=', typeof B);

b.js

exports = module.exports = B;
var A = require('./a');
function B() {
  console.log('I\'m B');
}
console.log('A=', typeof A);

I tried several approach in the Coffee-Script, but no one approach can do the exactly same like the javascript above.

Upvotes: 0

Views: 225

Answers (1)

go-oleg
go-oleg

Reputation: 19480

Having modules depend on each other doesn't sound like a good idea, but if its what you need, this works:

a.coffee

A = () ->
  console.log('I\'m A')

module.exports = A

B = require('./b')

console.log('B=', typeof B)

b.coffee

B = () ->
  console.log('I\'m B')

module.exports = B

A = require('./a')

console.log('A=', typeof A)

Please make sure you read the module cycles section of the node.js documentation (it talks about how a module may not finish executing before returning).

Upvotes: 1

Related Questions