在Nodejs回调函数中调用模块函数

5

我有一个模块,可以将日志写入到一个文件中。(使用 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

当我直接调用它时,它可以正常工作。但是当我从回调函数中调用它时,例如casperjs的启动事件:
h = require('./h').h
casper = require('casper').create()

casper.start "http://google.com", ()->
  h.log("hi")

casper.run()

我经常遇到类似于“未定义”的TypeError错误:

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

谷歌搜索并没有给出很多线索!
2个回答

3
CasperJS运行在PhantomJS(或SlimerJS)上并使用其模块。它与nodejs不同。PhantomJS的fs模块没有appendFile函数。
当然,如果在casper中使用,您可以使用fs.write(filepath, content, 'a');来追加文件。如果您仍然想在casper和node中都使用您的模块,则需要编写一些粘合代码。
function append(file, content, callback) {
    if (fs.appendFile) {
        fs.appendFile(file, content, callback);
    } else {
        fs.write(file, content, 'a');
        callback();
    }
}

谢谢指出这一点。知道casperjs在PhantomJS上运行而不是nodejs真的很有用,对于新手来说fs模块的差异并不明显,但这很有意义。 - B2F

0

我认为问题出在coffeescript上。尝试使用splat参数而不是依赖于arguments对象。

log(statements...)

如果那不起作用,你可能需要查看JavaScript输出或尝试在纯JavaScript中尝试相同的操作,看看是否会出现相同的错误。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接