需要一次文件并在任何地方使用它



我已经阅读了module.exports及其工作原理,但我不确定我是否可以用它完成我想要的 - 或者至少我不确定如何完成。我在文件中有一些帮助程序函数,其中一个函数用于项目中的大多数文件。我想知道是否可以只"需要"该文件一次,然后在需要时在整个项目中使用它。

我的文件看起来像这样:

不和谐的实用工具.js

const { MessageEmbed, Permissions } = require('discord.js')
module.exports = {
embedResponse (message, embedOptions, textChannel = null) {
const embed = new MessageEmbed()
if (embedOptions.color) embed.setColor(embedOptions.color)
if (embedOptions.title) embed.setTitle(embedOptions.title)
if (embedOptions.description) embed.setDescription(embedOptions.description)
if (embedOptions.url) embed.setURL(embedOptions.url)
if (embedOptions.author) embed.setAuthor(embedOptions.author)
if (embedOptions.footer) embed.setFooter(embedOptions.footer)
if (embedOptions.fields) {
for (const field of embedOptions.fields) {
embed.addFields({
name: field.name,
value: field.value,
inline: field.inline ? field.inline : false
})
}
}
if (textChannel) {
textChannel.send(embed)
return
}
message.embed(embed)
},
inVoiceChannel (voiceState, message, response = null) {
if (!voiceState.channel) {
this.embedResponse(message, {
color: 'RED',
description: response === null ? 'You need to be in a voice channel to use this command.' : response
})
console.warn(`${message.author.tag} attempted to run a music command without being in a voice channel.`)
return false
}
return true
},
isAdminOrHasPerms (user, permissionRole) {
return user.hasPermisssion(Permissions.FLAGS.ADMINISTRATOR) || user.hasPermission(permissionRole)
}
}

在几乎所有其他文件中,我都使用embedResponse函数。所以在项目中,我必须做require('discord-utils)然后做这样的事情:discordUtils.embedResponse(blahblah...)虽然这很好,但它似乎真的是多余的,因为我知道我将在任何地方使用它。我想知道是否有一种方法可以使用一个 require 语句并随时拉取我需要的功能?

您可以使用 NodeJS 中的global对象定义全局可访问的变量。但是,这在 NodeJS 中既不是常见模式,也不是推荐的模式。

global.foo = 1 // make the foo variable globally accessible

https://nodejs.org/api/globals.html#globals_global

Node.js实际上有一个整洁的小缓存系统,可以利用它来实现单例效果。首次require文件时,它会运行并设置module.exports。之后每次需要同一个文件时,它都会返回对第一个时间返回的同一对象的引用,而不是实际重新执行。

不过有一些注意事项。这并不总是保证文件不会再次执行。例如,有时如果您需要来自远离第一个位置的非常不同的位置的文件,它可能会重新执行该文件。就像您首先需要该文件作为require('./my-file'),然后需要它与require('../../../../my-file')一样,它有时可以重新执行它并清除缓存的引用。

相关内容

最新更新