Javascript 如何在单个模块中引用内部函数。导出
根据getCursor的不同,我有以下getOffsetCustom代码。我可以将getOffsetCustom和getCursor作为导出,但不知道如何将getCursor放在getOffsetCustom中 我正在使用此文件来运行节点而不构建系统。这是公开实用程序函数的最佳方法吗Javascript 如何在单个模块中引用内部函数。导出,javascript,node.js,node-modules,Javascript,Node.js,Node Modules,根据getCursor的不同,我有以下getOffsetCustom代码。我可以将getOffsetCustom和getCursor作为导出,但不知道如何将getCursor放在getOffsetCustom中 我正在使用此文件来运行节点而不构建系统。这是公开实用程序函数的最佳方法吗 module.exports = { getCursor: (rec) => Buffer.from(rec.toString()).toString("base64"), get
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 = { 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; }, };
- 使用方法(而不是箭头函数)和
:此
但是,这要求始终对模块对象调用该方法,因此,例如,您不能在导入时使用解构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