0

How does one define a function in one file (a.coffee), so that a NodeJS module in another file (b.coffee) can use it?

For example:

# a.coffee
b = require('./b')

getGreeting = (name) ->
  if name == "foo"
    "Hey, "
  else
    "Hello, "


b.greet "foo"



# b.coffee
module.exports =
  greet: (name) ->
    greeting = getGreeting name
    console.log greeting + name

Compiling this with coffee -bc *.coffee and running with nodejs a.js gives

ReferenceError: getGreeting is not defined
    at Object.module.exports.greet (/home/charlie/Desktop/NodeJSExtTest/b.js:5:16)
    at Object.<anonymous> (/home/charlie/Desktop/NodeJSExtTest/a.js:14:3)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:142:18)
    at node.js:939:3

I've also tried to use @getGreeting, but with the same result.

Extra information:

$ coffee -v
CoffeeScript version 1.10.0

$ nodejs -v
v5.9.1
2
  • b.coffee has no reference to getGreeting Commented Apr 2, 2016 at 17:20
  • @eosterberg I get that, but how would I give b that reference? For now, I'm doing in a: (eval b.greet.toString())("foo"), but that's just asking for problems. Commented Apr 2, 2016 at 23:54

1 Answer 1

1

You could inject getGreeting into module b e.g. as follows:

b.coffee:

module.exports = (getGreeting) ->
  greet: (name) ->
    greeting = getGreeting name
    console.log greeting + name

a.coffee:

b = require('./b')(getGreeting)
Sign up to request clarification or add additional context in comments.

2 Comments

Will this work too if the function getGreeting requires more variables from a.coffee? I want to split my main file in more smaller files, but they all need these variables, and they keep changing
Yes. The exterior function in the module b's code ((getGreeting) -> greet: ...) is executed like any other function within module a, and JavaScript's normal scoping rules apply for any function it may receives as an argument. So you can have something along these lines in module a: title = 'Mr. '; getGreeting = (name) -> if name == 'foo' then 'Hey, ' + title else 'Hello, ' + title, then b = require('./b')(getGreeting).

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.