Module function call inside 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

The file works when I call it directly. But when I call this from a callback, for example, casperjs fires an event:

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

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

casper.run()

... I always get this or the like "undefined" TyepError:

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

Googling it does not give a lot of clues!

+4
source share
2 answers

CasperJS runs on PhantomJS (or SlimerJS) and uses its modules. It is different from nodejs. PhantomJS fs module has no function 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();
    }
}
+2

, coffeescript. splat , arguments.

log(statements...)

, javascript JavaScript , .

0

All Articles