Calling a module function inside a Nodejs callback

I have a module that writes to a log file. (coffeescript sorry, but you get the idea!)

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

It works file when I call it directly. But when I call it from a callback, for example casperjs start event:

h = require('./h').h
casper = require('casper').create()

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

casper.run()

... I always get this or similar "undefined" TyepError:

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

Googling this doesn't give many clues!

CasperJS runs on PhantomJS (or SlimerJS) and uses its modules. It is distinct from nodejs. PhantomJS' fs module doesn't have an appendFile function.

Of course you can use fs.write(filepath, content, 'a'); to append to a file if used in casper. If you still want to use your module both in casper and node then you need to write some glue code like

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

I think the problem is with the coffeescript. Try using a splat parameter instead of relying on the arguments object.

log(statements...)

If that doesn't work, you might need to look at the javascript output or try the same thing in plain JavaScript and see if you get the same error.