如何在一个文件(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
答案 0 :(得分:1)
您可以将getGreeting
注入模块b,例如如下:
b.coffee:
module.exports = (getGreeting) ->
greet: (name) ->
greeting = getGreeting name
console.log greeting + name
a.coffee:
b = require('./b')(getGreeting)