【问题标题】:Calling a module function inside a Nodejs callback在 Nodejs 回调中调用模块函数
【发布时间】:2014-08-26 03:16:00
【问题描述】:

我有一个写入日志文件的模块。 (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 start 事件:

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

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

casper.run()

...我总是得到这个或类似的“未定义”类型错误:

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

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

【问题讨论】:

    标签: node.js casperjs


    【解决方案1】:

    CasperJS 在 PhantomJS(或 SlimerJS)上运行并使用其模块。它与 nodejs 不同。 PhantomJS 的 fs module 没有 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 模块对于新手来说并不明显,但它很有意义。
    【解决方案2】:

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

    log(statements...)

    如果这不起作用,您可能需要查看 javascript 输出或在纯 JavaScript 中尝试相同的操作,看看是否遇到相同的错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 2014-01-24
      • 2021-09-26
      • 2013-11-04
      • 2019-07-06
      • 2016-07-06
      相关资源
      最近更新 更多