在Node.js中导出变量时出错

时间:2018-09-01 15:00:55

标签: javascript node.js node-modules

我要导出变量。但这会发生

第一个文件

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'

    }

}

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

第二个文件

const commando = require('discord.js-commando');
const ytdl = require('ytdl-core');
var Testotest = require('./test.js')


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

    }


    async run(message, args) {

        message.channel.send(Testotest.Testo())

    }

}

module.exports = pauseCommand;

错误

ReferenceError: Testo is not defined
    at Object.<anonymous> (/Users/andrew/Desktop/NullBot_/commands/music/test.js:27:24)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/andrew/Desktop/NullBot_/commands/music/pause.js:3:17)
    at Module._compile (module.js:652:30)

为什么会出现错误?

3 个答案:

答案 0 :(得分:0)

您可能会想以这种方式使用module.exports

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

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

答案 1 :(得分:0)

您已定义此文件,我知道是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,因此,将出现错误。 如果要解决此问题,则需要在“运行”方法之外定义“ var Testo”或使该模块异步。

致谢

答案 2 :(得分:0)

您在方法Testo中定义了run 如果您运行方法run Testo = 'hello',但是您定义了class testCommand,因此Testoundefined,则将运行方法run搁置一次以进行定义Testo

此代码

module.exports.Testo = Testo;

设置module.exports = {Testo: Testo}

但是您使用

module.exports = testCommand;

设置module.exports = testCommand

致电时,Testotest.TestotestCommand.Testo(未定义)

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

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