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

How to Reference internal function in single module.exports

根据 getCursor,我有以下带有 getOffsetCustom 的代码。我可以同时访问 getOffsetCustom 和 getCursor 作为导出,但无法弄清楚如何在 getOffsetCustom 中使用 getCursor。

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

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;
  },
};

三种方法:

  • 仅供参考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,
    });
    

    这里唯一的缺点(或优点?)是不能从外部hotpatched/mocked导出,getOffsetCustom将始终引用本地getCursor