Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 499
Dolbery Avatar asked Oct 20 '22 02:10

Dolbery


1 Answers

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();
    }
}
like image 180
Artjom B. Avatar answered Oct 23 '22 03:10

Artjom B.