简体   繁体   中英

I cannot access the variable in the other script. (Module.exports don't work everywhere)

I have been having issues with module.exports .
I have 2 Scripts that use Discord.js , and i need to have a SetTimeout() variable that is common to both scripts to be able to use ClearTimeout() from each of them.
I tried to use:

//first script
var foo = 20;
module.exports.foo = foo;
//Second Script
var exp = require('./firstscript');
console.log(exp.foo);

This was a test, to see if i was doing it the wrong way, with a simple variable instead of my SetTimeout().
The test worked fine when i ran new scripts with the node command
but with npm start on my 2 original scripts it returned 'undefined' while having the same syntax.

In every script is already a module.exports for the Discord.js event class like 'Ready' for exemple.
I'm running this bit of code outside the main module.exports at the top where the const are declared.
I wonder if this is causing my issue.

example:

//the code i'm talking about is here.

module.exports = class ReadyEvent extends BaseEvent {
  constructor() {
    super('ready');
  }
  
  async run(client) {
 

Thanks for your help.
Ask me for clarification if needed.

EDIT:
I looked up on the internet to see if it was an issue with the module.export that was already present on the script. And it was.

Apparently you cannot have several module.export in a script if each one of them doesn't specify a variable:

//this doesn't work
module.exports.value = value;
module.exports = value2;
//this works
module.exports.value = value;
module.exportd.value2 = value2;

My problem was that the one already present was used by the 'discord.js compiler' to register every command so i couldn't modify it without breaking the bot.

I decided to put my timer in a new script named GlobalVars and it worked Perfectly fine.
I'm Satisfied that it works now.
For me the issue is fixed but i would love to know if it is possible to export a variable WITH the discord.js module.exports syntax included.

From your Second Script variable, its seems to be requiring a folder and not a file, and I don't think folders are allowed.

Assuming you are requiring a script and not a folder:

First Mistake: When requiring, inside the brackets you must have quotation marks ( "" ) or ( '' ).

If it is a folder, add a / next to ./firstscript and assign it to the file you want to refer to.

var exp = require('./firstscript/THE_INTENDED_FILE');

... If firstscript is a json file:

var exp = require('./firstscript.json');

Extracting Variables from file

// Option 1:
console.log(exp.foo);
// Option 2:
const extract = exp.foo
console.log(extract);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM