Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
77
rated 0 times [  78] [ 1]  / answers: 1 / hits: 5865  / 5 Years ago, wed, february 20, 2019, 12:00:00

I'm trying to create my own lorem ipsum app and I want to keep my code clean by storing my word bank in other files. How can I access an array stored in a different JS file? For example, instead of hardcoding harry = [, , ], I want to store that data in a different file and just call that file into the array.



// generator.js
function GenerateNewText(){
this.sentences = [
harry = [
I am the chosen one!,
Boy wizard,
Quidditch seeker
ron = [
I am a Weasley,
Gryffindor,
Quidditch keeper
]
]
}

GenerateNewText.prototype.getRandomSentence = function() {
let randomSentence = this.sentences[0][Math.floor(Math.random() * this.sentences.length)]
return randomSentence;
}


Currently, I have a harryText.js which contains



// harryText.js
harryText = [
I am the chosen one,
I am a Gryffindor,
I am a boy
]

module.exports = harryText;


but doing this in my generator.js shows harryText is not defined



function GenerateNewText(){
this.sentences = [
harryText, <---- error here
ron = [
I am a Weasley,
Gryffindor,
Quidditch keeper
]
]
}


I tried requiring it like so
const harryText = require(./harryText.js)
and the problem persists. I'm guessing a scope issue?



I tried installing ejs and changing harryText.ejs and including it like <%= include harryText %> in the generator array and that's invalid code.



Is calling an array from another file and storing it within another array even possible? Does anyone know a solution to this?



And yes, I know a Harry Potter Ipsum already exists. This is just dummy text.


More From » arrays

 Answers
2

Javascript files are isolated from each other. To share common code you always need require and module.exports



So you are doing the right thing with module.exports = harryText



You then need to require that file in generator.js



const harryText = require(./harryText);
function GenerateNewText(){
this.sentences = [
harryText,
ron = [
I am a Weasley,
Gryffindor,
Quidditch keeper
]
]
}


[#8827] Tuesday, February 19, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriel

Total Points: 323
Total Questions: 107
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;