Javascript 在nodejs中导出变量时出错

Javascript 在nodejs中导出变量时出错,javascript,node.js,node-modules,Javascript,Node.js,Node Modules,我想导出一个变量。但这种情况会发生 第一档 第二档 错误 为什么会出现错误 您的mayby gaonna希望以这种方式使用module.exports module.exports = { key1: val1, key2: val2 } 因此,您的代码module.exports.Testo=Testo;module.exports=testCommand;可以使用此格式,并且不会引发错误。您定义了此文件,我知道是test.js: const commando = requi

我想导出一个变量。但这种情况会发生

第一档

第二档

错误


为什么会出现错误

您的mayby gaonna希望以这种方式使用module.exports

module.exports = {
    key1: val1,
    key2: val2
}

因此,您的代码module.exports.Testo=Testo;module.exports=testCommand;可以使用此格式,并且不会引发错误。

您定义了此文件,我知道是test.js:

const commando = require('discord.js-commando');
const ytdl = require('ytdl-core');


class testCommand extends commando.Command {
    constructor(client) {
        super(client,{
            name: 'test',
            group: 'music',
            memberName: 'test',
            description: 'test',
        });

    }

    async run(message, args) {
      var Testo = 'hello'
    }
}

// Testo is not defined because is under method run
module.exports.Testo = Testo;
module.exports = testCommand;
您现在可以更好地看到这个问题,因为它缩进得很好。此模块正在加载同步,而您正在按照同步方式导出Testo,因此,预期会出现错误。 如果您想解决这个问题,您需要在run方法之外定义var Testo或使这个模块异步

关于

您在方法运行中定义了Testo 若您运行方法runtesto='hello',但您定义了类testCommand,所以Testo是未定义的,那个么您应该运行方法run一次来定义Testo

此代码

module.exports.Testo = Testo;
set module.exports={Testo:Testo}

但是你用

module.exports = testCommand;
set module.exports=testCommand

当您调用Testotest.Testo时,testCommand.Testo是未定义的

更改第一个文件中的代码:

module.exports = testCommand;
module.exports.Testo = Testo;

看起来您正在立即覆盖exports.testo,请尝试将最后一个导出行更改为沿着这些行的内容module.exports.testCommand=testCommand;如果我需要导出一个必须运行的函数,但我还需要导出一个变量中的函数,以便在另一个文件中使用,该怎么办;那么,有没有一种方法可以在“run”函数中导出变量?而不将module.exports放在run函数中
module.exports.Testo = Testo;
module.exports = testCommand;
module.exports = testCommand;
module.exports.Testo = Testo;