简体   繁体   English

如何通过 module.exports 导出这个名为 function 的文件?

[英]How do I export this named function through module.exports?

I have a command file for a discord bot that contains the command and a piece of parsing logic contained within a function that I want to reuse within my index.js我有一个 discord 机器人的命令文件,其中包含我想在我的index.js中重用的 function 中包含的命令和一段解析逻辑

// file: ./commands/scrumPrompt.js

// The function

const extractDeets = function (f, scrum) {
  let items = [];
  let re = new RegExp("(\n[ -]*" + f + ".*)", "g");
  let replace = new RegExp("[ -]*" + f + "[ ]+");
  for (const item of scrum.matchAll(re)) {
    items.push(item[1].trim().replace(replace, ""));
  }

  return items;
};


// The actual command itself within the same file
module.exports = {
  name: "scrum",
  usage: `!scrum < followed by your message >  as per Standup format - refer !show for showing the format`,
  description: "Reply to standup prompt",
  async execute(message, args) {
    if (message.channel.type === "text") {
      if (!args.length)
        return message.reply(
          "Please Provide your scrum as per the format in help menu !scrum < your message >"
        );
      else {
        if (message.author.id !== -1) {
          const client = new MongoClient(MONGO_URI);

          try {
            const database = client.db(DB_NAME);
            const members = database.collection("members");

            const query = { user_id: message.author.id };
            const membersdetail = await members.findOne(query);

            if (membersdetail !== null) {
              // since this method returns the matched document, not a cursor, print it directly
              //console.log("Adding Scrum for ", membersdetail.email);

              let userscrum = args.splice(0).join(" ");

              // Check if multiple !scrum commands are present in developer scrum message
              if (userscrum.includes("!scrum") == false) {
                // Expects notations of "-" to exist
                let [f, e, b, o, bl] = ["f", "e", "b", "o", "x"];

                let features = extractDeets(f, userscrum);
                let enhancements = extractDeets(e, userscrum);
                let bugs = extractDeets(b, userscrum);
                let others = extractDeets(o, userscrum);
                let blockers = extractDeets(bl, userscrum);
    .
    .
    .
};

I want to keep the name of the function as extractDeets() itself so that it doesn't mess with the usage within the command as well.我想将 function 的名称保留为extractDeets()本身,这样它也不会与命令中的用法混淆。 I'm not completely sure how to export it into the index.js because it's already kind of being imported here:我不完全确定如何将它导出到index.js ,因为它已经在这里被导入了:

// Imports the command file + adds the command to the bot commands collection
for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  bot.commands.set(command.name, command);
}

I'm unsure of how to add the function as another import, maybe I should export it into another file and then import it from there?我不确定如何将 function 添加为另一个导入,也许我应该将它导出到另一个文件然后从那里导入? I'm not sure if that's possible or doable here.我不确定这在这里是否可行或可行。 I've tried directly importing from here but then the command doesn't work, which is troublesome.我试过直接从这里导入,但是命令不起作用,很麻烦。

You can do it like this:你可以这样做:

module.exports = { extractDeets };

Later, you can import it like this:稍后,您可以像这样导入它:

const { extractDeets } = require('../your_file');

如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在节点 js 中使用 module.exports 导出数组? - How do I export an array with module.exports in node js? 尝试将中间件功能导出到module.exports对象时,为什么会得到“下一个不是功能”的信息? - Why do I get 'Next is not a function' when I try to export a Middleware function to module.exports object? 如何使用module.exports导出异步功能 - How to use module.exports to export async function 如何更改module.exports进行导入和导出? - How to change module.exports to import and export? 我们如何在 nodeJS 中使用 module.exports 返回函数? - How do we return function using module.exports in nodeJS? 带函数的 module.exports - module.exports with function module.exports:不是函数 - module.exports: is not a function 如何修复“无法分配给 object 的只读属性“导出”'#<object> ' 将第二个 function 添加到 module.exports 时?<div id="text_translate"><p> 不幸的是,我已经被困了大约 5 天了。 我用谷歌搜索过,没有什么对我有用。 我有一个 utils.js 文件,里面有很多东西可以帮助我。 当我将 function "doesUserContainRoles" 添加到导出时,我的 Chrome 控制台给了我错误:</p><blockquote><p> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;'</p></blockquote><p> 当我删除 function 时,utils 文件中的所有内容都可以完美运行,根本没有 0 个问题。 只要我添加 function,我就会收到此错误。 我通过以下方式要求 utils 文件:</p><pre class="lang-js prettyprint-override"> const utils = require("../../../utils");</pre><p> 并且没有与此一起使用的import 。 (我知道module.exports和import不能一起工作)</p><p> 我正在使用什么:</p><ul><li><p> Vue.js @vue/cli 4.5.8</p></li><li><p> Node.js v15.2.0</p></li></ul><h3> 文件:</h3><p> utils.js</p><pre class="lang-js prettyprint-override"> const winston = require("winston"); const { datadog } = require("./credentials.js"); const { createLogger, format, transports } = require('winston'); const base_url = "http://localhost:3001/api/v1" // Winston ~ const httpTransportOptions = { host: datadog.logger.host, path: datadog.logger.path, ssl: datadog.logger.ssl }; const customLevels = { levels: { emergency: 0, alert: 1, critical: 2, error: 3, warn: 4, notice: 5, info: 6, debug: 7, success: 8 }, } const logger = createLogger({ level: 'info', levels: customLevels.levels, exitOnError: false, format: format.json(), transports: [ new transports.Http(httpTransportOptions), ], }); const commonMessages = { accessPage: "User Accessed a Page", restrictedPage: "Attempt at accessing restricted page" } function alertGeneral() { alert("Oops. An error has occurred. Please try again later, If this problem continues. please contact Vinniehat;"), } function doesUserContainRoles(userRoles. containsRoles) { return.;userRoles.some(role =&gt; containsRoles,includes(role)), } module,exports = { logger, commonMessages, base_url, alertGeneral, doesUserContainRoles }</pre><p> 这是错误堆栈:</p><pre> Uncaught TypeError: Cannot assign to read only property 'exports' of object '#&lt;Object&gt;' at Module.eval (utils.js?1b23:45) at eval (utils.js:68) at Module../utils.js (app.js:1944) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (router.js?9883:19) at Module../src/router/router.js (app.js:1812) at __webpack_require__ (app.js:854) at fn (app.js:151) at eval (main.js:34)</pre><p> 我也尝试使用export default 。 这样做时,我的前端工作。 网站加载没有错误。 不过,我的后端使用 Express.js 运行,然后引发错误:</p><pre> Unhandled rejection E:\Development\Websites\iceberg-gaming-website\utils.js:45 export default { ^^^^^^ SyntaxError: Unexpected token 'export' at wrapSafe (node:internal/modules/cjs/loader:1018:16) at Module._compile (node:internal/modules/cjs/loader:1066:27) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at Object.&lt;anonymous&gt; (E:\Development\Websites\iceberg-gaming-website\express\modules\user.js:9:15) at Module._compile (node:internal/modules/cjs/loader:1102:14) at Object.Module._extensions..js (node:internal/modules/cjs/loader:1131:10) at Module.load (node:internal/modules/cjs/loader:967:32) at Function.Module._load (node:internal/modules/cjs/loader:807:14) at Module.require (node:internal/modules/cjs/loader:991:19) at require (node:internal/modules/cjs/helpers:92:18) at E:\Development\Websites\iceberg-gaming-website\express\express.js:27:27 at tryCatcher (E:\Development\Websites\iceberg-gaming-website\node_modules\bluebird\js\release\util.js:16:23)</pre></div></object> - How do I fix 'Cannot assign to read only property 'exports' of object '#<Object>' when adding a 2nd function to module.exports? 如何为“ module.exports”函数创建定义 - How to create a definition for 'module.exports' function 如何将.then() function 的响应放入module.exports 中? - How to put the response of .then() function in module.exports?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM