【问题标题】:node.js module self talk back to js that requires itnode.js 模块自我与需要它的 js 对话
【发布时间】:2025-12-04 13:00:02
【问题描述】:

我在理解如何在 app.js 和模块之间“上下”交流时遇到问题...

我认为它带有回调,但我也看到了 self._send()、this.send() 和 module.exports.emit 之类的东西

我很困惑。

我最近从 npm 安装了 pdfkit(相当不错的 6/10 :p)我想通过为 doc.write() 添加一个 done 事件/回调来稍微改进它来学习。

我知道它不是那么重要,但我一直在查看我安装的模块,这可能是最简单的代码示例,不会伤害到“完成”我还认为这个函数会很好学习因为它使用 fs.writeFile,它有一个 function(){},它在编写完成时触发,所以我可以看到它在代码中的结束位置,这使它成为一个简单的学习工具。

我已经修改了几次代码,试图比较模块以查看在哪里完成了类似的事情,但我只是不断地用错误打破它,我觉得我没有得到任何地方:

在 pdfkit 模块 document.js 中我进行了更改:

var EventEmitter = require('events').EventEmitter;//ben
module.exports = new EventEmitter();//ben


PDFDocument.prototype.write = function(filename, fn, callback) {//ben added callback
  return this.output(function(out) {
    return fs.writeFile(filename, out, 'binary', fn, function(){//ben added finished function
      //module.exports.emit('pdf:saved');//ben
      callback();//ben
      });
  });
};

在我的 app.js 中:

doc.write('public_html/img/'+_.c+'_'+_.propertyid+'.pdf',function(){console.log('pdf:saved');});

//doc.on('pdf:saved',function(){console.log('pdf:saved');});

我也不确定我在谷歌上查询的是什么,请有人帮助我吗?

【问题讨论】:

    标签: node.js node-modules


    【解决方案1】:

    需要 EventEmitter 来创建具有事件存储的对象,并发出/捕获事件。
    虽然您在示例中使用的称为“回调”。

    这是两种不同的方式,可以交叉使用。有时使用事件很好,但有时只需回调就足够了。

    了解它的最佳方式:玩回调(暂时忘记事件)。尝试考虑回调的不同用途,甚至可能有回调函数并传递它。然后来到回调链。只有在开始使用EventEmitter 之后。请记住,EventEmitter 与回调不同,有时可以兼容用例,但通常用于不同的情况。

    这是您的代码,使用与您拥有/需要 atm 相同的功能进行了简化:

    PDFDocument.prototype.write = function(filename, callback) {
      this.output(function(out) {
        fs.writeFile(filename, out, 'binary', callback);
      });
    };
    

    并按照您已经使用的方式使用它。
    不要试图生成只会使一切复杂化的代码垃圾 - 最好单独研究特定领域,然后切换到下一个。不然脑子会乱的。

    【讨论】:

    • 我尝试了您的简单代码,但我从未从回调 doc.write('public_html/img/'+_.c+''+.propertyid+ 中看到 console.log '.pdf',function(){console.log('pdf:saved');});
    • 你确定this.output会调用自己的回调函数吗?
    【解决方案2】:

    已修复

    fn 是回调函数!

    PDFDocument.prototype.write = function(filename, fn) {
      return this.output(function(out) {
        return fs.writeFile(filename, out, 'binary', fn);
      });
    };
    

    并将我的回调函数命名为 fn 即可!

    doc.write('public_html/img/'+_.c+'_'+_.propertyid+'.pdf',function fn(){console.log('pdf:saved');});
    

    对我来说,这是一座巨大的学习高峰!

    【讨论】:

      最近更新 更多