如何在单个module.exports中引用内部函数

时间:2020-11-10 21:02:53

标签: javascript node.js node-modules

根据getCursor,我将以下代码与getOffsetCustom一起使用。我可以将getOffsetCustom和getCursor都导出,但无法弄清楚如何将getCursor包含在getOffsetCustom中。

我将此文件用于没有和构建系统的运行节点。这是公开实用程序功能的最佳方法吗?

module.exports = {
  getCursor: (rec) => Buffer.from(rec.toString()).toString("base64"),
  getOffsetCustom: (data, afterCursor) => {
    const offsetBasedOnFind = data.findIndex(
      (rec) => getCursor(rec.id) === afterCursor
    );
    return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
  },
};

1 个答案:

答案 0 :(得分:1)

三种方法:

  • 仅引用module.exports

    module.exports = {
      getCursor: (rec) => Buffer.from(rec.toString()).toString("base64"),
      getOffsetCustom: (data, afterCursor) => {
        const offsetBasedOnFind = data.findIndex(rec =>
          module.exports.getCursor(rec.id) === afterCursor
    //    ^^^^^^^^^^^^^^^
        );
        return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
      },
    };
    
  • 使用方法(而不是箭头函数)和this

    module.exports = {
      getCursor(rec) {
        return Buffer.from(rec.toString()).toString("base64");
      },
      getOffsetCustom (data, afterCursor) {
        const offsetBasedOnFind = data.findIndex(rec =>
          this.getCursor(rec.id) === afterCursor
    //    ^^^^^
        );
        return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
      },
    };
    

    这要求始终始终在模块对象上调用该方法,例如,您不能在导入上使用解构。

  • 声明常规函数,然后将其导出。这将是首选方法:

    function getCursor(rec) {
      return Buffer.from(rec.toString()).toString("base64");
    }
    function getOffsetCustom (data, afterCursor) {
      const offsetBasedOnFind = data.findIndex(rec =>
        getCursor(rec.id) === afterCursor
      );
      return offsetBasedOnFind === -1 ? 0 : offsetBasedOnFind + 1;
    }
    Object.assign(exports, {
      getCursor,
      getOffsetCustom,
    });
    

    这里唯一的缺点(或优势?)是无法从外部对出口进行热修补/模拟,getOffsetCustom将始终引用本地getCursor