node.js - 从 Node.js 公开方法的最佳方式是什么?

标签 node.js module

假设我想公开一个名为 Print 的方法

  1. 作为原型(prototype)的绑定(bind)方法:

文件另存为 Printer.js

var printerObj = function(isPrinted) {
            this.printed = isPrinted;        
    }

printerObj.prototype.printNow = function(printData) {
        console.log('= Print Started =');
};
module.exports = printerObj;

然后通过将代码 require('Printer.js').printNow() 放入任何外部 .js Node 程序文件中来访问 printNow()

  1. 使用 module.exports 导出方法本身:

文件另存为 Printer2.js

var printed = false;   
function printNow() {
console.log('= Print Started =');
}    
module.exports.printNow = printNow;

然后通过将代码 require('Printer2.js').printNow() 放入任何外部 .js Node 程序文件中来访问 printNow()

谁能说出它与 Node.js 的区别和最佳实现方式是什么?

最佳答案

当然是第一种方式。它被称为 substack pattern,您可以在 Twitter 上阅读它。以及 Mikeal Rogers 的 blog .一些代码示例可以在 jade github repo 中找到。在解析器中:

var Parser = exports = module.exports = function Parser(str, filename, options){
  this.input = str;
  this.lexer = new Lexer(str, options);
  ...
};

Parser.prototype = {

  context: function(parser){
    if (parser) {
      this.contexts.push(parser);
    } else {
      return this.contexts.pop();
    }
  },

  advance: function(){
    return this.lexer.advance();
  }
};

关于node.js - 从 Node.js 公开方法的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14516717/

相关文章:

node.js - 为什么我们需要快速正文解析器?

json - 循环遍历 JSON 对象的正确方法

javascript - 通过 PowerBI API 在嵌入 View 中创建报告

c - 从 Apache 模块获取套接字

Magento - 创建新的客户属性

javascript - 如何在redis中使用单个键插入多个json数据

javascript - Node.js websocket.io 光标示例 我看不到它?

模块依赖 : is it possible to set a mininum version?

perl - 为什么 Perl 模块 Crypt::SSLeay 在加载时出错?

TypeScript:指定目录以查找模块类型定义