我在理解如何在 app.js 和模块之间“上下”交谈时遇到问题......
我认为它带有回调,但我也看到了 self._send()、this.send() 和 module.exports.emit 之类的东西
我很困惑。
我最近从 npm 安装了 pdfkit(相当不错的 6/10 :p)我想通过为 doc.write() 添加完成事件/回调来稍微改进它来学习。
我知道它不是那么重要,但我一直在查看我安装的模块,这可能是最简单的代码示例,不会伤害到“完成”我还认为这个函数在使用时会很好学习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');});
我也不确定我在谷歌上查询什么,请有人帮助我吗?