0

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?

DaCurse
  • 795
  • 8
  • 25
Goose
  • 1
  • 1
  • Does this answer your question? [Share variables between files in Node.js?](https://stackoverflow.com/questions/3922994/share-variables-between-files-in-node-js) – Wyck Feb 19 '20 at 04:20
  • You can use a JSON file to store the array in it, then read/write to it. – DaCurse Feb 19 '20 at 19:55

3 Answers3

2

global_data.js

export const YourArray = ... //whatever info

referencing this:

import { YourArray } from './global_data';
David
  • 15,894
  • 22
  • 55
  • 66
  • Using this code, my bot crashes upon start with the following error: > /home/container/commands/admin commands/say.js:11 > import { allowed } from './global_data.js'; > SyntaxError: Unexpected token { – Goose Feb 19 '20 at 13:19
  • @Goose What version of Node are you using? `node -v` – slothiful Feb 19 '20 at 13:45
  • Use `require` instead of import. – DaCurse Feb 19 '20 at 20:55
  • @slothiful I'm unsure, when I try running `node -v`, it doesn't do anything. – Goose Feb 19 '20 at 21:22
  • Open command prompt and execute it, don't run it as code if that's what you're doing. Most likely you're on an earlier version of Node that doesn't support ES6 modules/imports. Updating should fix your error with this. – slothiful Feb 19 '20 at 21:41
  • Am I doing this wrong? It's not doing anything. ._. https://ibb.co/DVGDPLJ – Goose Feb 19 '20 at 23:54
0

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
}
Ezani
  • 535
  • 3
  • 18
0

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.

Rick Maior
  • 56
  • 6