NodeJS CoffeeScript外部文件范围

时间:2016-04-02 15:18:40

标签: node.js coffeescript

如何在一个文件(a.coffee)中定义一个函数,以便另一个文件(b.coffee)中的NodeJS模块可以使用它?

例如:

# 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

使用coffee -bc *.coffee进行编译并使用nodejs a.js运行

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

我也尝试使用@getGreeting,但效果相同。

额外信息:

$ coffee -v
CoffeeScript version 1.10.0

$ nodejs -v
v5.9.1

1 个答案:

答案 0 :(得分:1)

您可以将getGreeting注入模块b,例如如下:

b.coffee:

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

a.coffee:

b = require('./b')(getGreeting)