node.js – 在Nodejs回调中调用模块函数

我有一个写入日志文件的模块. (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()

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

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

谷歌搜索这并没有提供很多线索!

最佳答案 CasperJS在PhantomJS(或SlimerJS)上运行并使用其模块.它与nodejs不同. PhantomJS’
fs module没有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();
    }
}
点赞