Reputation: 1
i'm here to ask if I put a variable in my index.js file like this: var allowed = ['id1', 'id2']
Could I use that variable across multiple files (e.g. commands?)`
I tried that in my bot but the console returned the error "allowed" is not defined. Anybody got a solution?
Upvotes: 0
Views: 1511
Reputation: 56
For being able to use a variable in diferent files you can define the variable the normal way you would do in the main file, then at the end of the file you can do module.exports to export the varible, lets say this is on index.js:
let variable1 = "Hello"
module.exports = {
variable1
}
Then on the 2º file where you want to use the variable you would require the index.js and that would have every variable that was exported
const variableX = require("./index.js")
console.log(variableX)
And as you can see, on the 2º file you would have on console.log "Hello".
Note: inside the require you put the path to the file you want to get the data from.
Upvotes: 0
Reputation: 557
Put the array variable at the top most of your file before defining any functions to make it global (or put it outside all the functions). Global functions can be used by any functions within the javascript file and across multiple files. If a variable is declared within the function, it can only be used within that function.
Example:
var a;
function f1() {
// a can be used here
}
function f1() {
// a can be used here
}
but
function f1() {
var b;
// b can only be used inside this function only
}
Upvotes: 0
Reputation: 16277
global_data.js
export const YourArray = ... //whatever info
referencing this:
import { YourArray } from './global_data';
Upvotes: 2