在Nodejscallback中调用一个模块函数

我有一个写入日志文件的模块。 (coffeescript抱歉,但你明白了!)

require = patchRequire(global.require) fs = require('fs') exports.h = log: ()-> for s in arguments fs.appendFile "log.txt", "#{s}\n", (e)-> if (e) then throw e 

当我直接调用它时它工作文件。 但是当我从callback中调用它,例如casperjs启动事件:

 h = require('./h').h casper = require('casper').create() casper.start "http://google.com", ()-> h.log("hi") casper.run() 

…我总是得到这个或类似的“未定义”TyepError:

 TypeError: 'undefined' is not a function (evaluating 'fs.appendFile("log.txt", "" + s + "\n", function(e) { if (e) { throw e; } })') 

谷歌search这并没有给出很多线索!

CasperJS在PhantomJS(或SlimerJS)上运行并使用其模块。 它不同于nodejs。 PhantomJS的fs模块没有appendFile函数。

当然你可以使用fs.write(filepath, content, 'a'); 附加到一个文件,如果在casper中使用。 如果你仍然想在casper和node中使用你的模块,那么你需要写一些胶水代码

 function append(file, content, callback) { if (fs.appendFile) { fs.appendFile(file, content, callback); } else { fs.write(file, content, 'a'); callback(); } } 

我认为问题是与咖啡的脚本。 尝试使用splat参数,而不是依靠参数对象。

log(statements...)

如果这不起作用,您可能需要查看JavaScript输出或在普通JavaScript中尝试相同的操作,并查看是否出现相同的错误。