Ways to retrieve an array saved in another JavaScript document

I am in the process of developing my own lorem ipsum application and keen on maintaining clean code by storing my word bank in separate files. How can I retrieve an array stored in a different JavaScript file? Rather than manually inputting harry = ["", "", ""], my goal is to store this information in an external file and then simply incorporate that data 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;
}

Presently, there exists a file named harryText.js which consists of:

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

module.exports = harryText;

However, when attempting to utilize this in generator.js, the error harryText is not defined arises.

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

I have tried importing it using

const harryText = require("./harryText.js")
but the issue persists. Could this be a scope problem?

An attempt was made to install ejs and change harryText.ejs followed by including it as <%= include harryText %> in the generator array, however, this resulted in invalid code.

Is it feasible to fetch an array from another file and embed it within a different array? Is there anyone who possesses a solution to this?

Also, I am aware that a Harry Potter Ipsum already exists. The text I am working with is solely for practice purposes.

Answer №1

To ensure that Javascript files can share common code, it is important to use require and module.exports

By using module.exports = harryText, you are on the right track.

Next, make sure to require that file in generator.js

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

Answer №2

For those utilizing ES6, the following approach can be taken.

//script1.js
  export const potterQuotes = [
     "I must not tell lies",
     "Expecto Patronum",
     "Always"
  ]

//script2.js
  import {potterQuotes} from './script1.js';
  // utilize the variable here 

Answer №3

UPDATE 2/20/19 16:15 I encountered the harryText is not defined error due to my own mistake of wrongly defining the variable. Initially, I defined it outside of the function GenerateNewText, then attempted defining it inside the this.sentence. The correct approach would have been to define it inside the function GenerateNewText and outside this.sentence, as illustrated below

function GenerateNewText(){
  const harryText = require("./harryText");
  const ronText = require("./ronText");
  this.sentences = [
    harryText,
    ronText
  ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

React / Next.js Rendering Problem, Data Discrepancy Between Client and Server

A new feature has been added to a webpage where an image background and a city name are displayed on top of it. The data file that generates these image backgrounds and city data consists of a standard array of objects. The challenge lies in dynamically l ...

Enhancing Javascript functionality with additional on.change customization opportunities

My website currently has a dynamic AJAX script that updates a table based on the selection from a dropdown menu with the ID of [id="afl_player_ID"]. However, I am looking to extend this functionality so that the same script runs when either [id="afl_playe ...

Having difficulty retrieving text data from a web URL using JavaScript

I am trying to extract text data from a web URL () My approach involved using two node modules. 1) Using crawler-Request it('Read Pdf Data using crawler',function(){ const crawler = require('crawler-request'); functio ...

Sustain information across two pages using Next.js

Recently, I have been considering reorganizing my Next.js webapp to allocate different pages for handling various screens. Currently, I have a component that manages multiple states to determine the screen being displayed. Within the jsx section, I utilize ...

Prevent the href from navigating to the next page when a doubleclick event listener is triggered

In my project, I am using an anchor tag that redirects to another page. However, if the user double clicks on it, I want to prevent the default behavior and stop the redirection. <a href="{location}">My Link</a> element.addEventListen ...

Can saving data within a mongoose pre-save hook initiate a continuous loop?

Currently, I am developing an API for a forum system which includes functionalities for users, forums, and posts. In my MongoDB Database, there is a 'categories' collection where each category acts as a container for a group of forums. Each categ ...

Production environment encountering a 404 error from API

I am currently working on a next.js application and I am facing an issue with setting up an API. Interestingly, when I run the app in development mode, the APIs get called successfully. However, if I try to run it using next start, I encounter a 404 error ...

While running on Windows 10, I attempted to execute the command "yarn add protobufjs" but encountered an unexpected issue. The error message displayed was: "An unexpected error occurred: E

After running the command yarn add protobufjs on my Windows 10 operating system, I encountered the following error message: \**>yarn add protobufjs [1/4] Resolving packages... [2/4] Fetching packages... error An unexpected error occurred: "EPERM: ...

What could be causing my click() function to only work properly after resizing?

It's driving me crazy. The code snippet below works perfectly, but not in my project. Only the code in the resize() function seems to work. When I resize the window, everything functions as expected - I can add and remove the 'open' class by ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...

Deliver the event to the parent class in Node.js

As I work with nodejs, one of the tasks in my main function is to create objects that emit events. One such object is called digitalInput, which will be responsible for listening to the gpio. The structure of the digitalInput class is as follows: class d ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

When using $http post in Angular, I encountered an issue with an unhandled rejection error

After successfully setting up my $http post request in Angular, I encountered an issue when refreshing the page. The console displays the following error: Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest": ...

Exploring the Fusion of Different Styles in Material-UI Using React

I have two different styles that I use in my code. One style is specific to certain components, while the other style is global and used across various components. For example, consider the following file tree: index.tsx -App.tsx -globalConstants.ts In ...

Obtain data from an HTML webpage, following the reception of data from the server through Node.js

Is there a way to achieve a functionality where submitting a form with the POST method on a webpage results in receiving an HTML page with a loading indicator that later gets completed to reveal the data? How can this be implemented using nodejs? ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

Clear SELECT After Submission

I have a jQuery script and need a function to reset the SELECT input after it has been submitted. <script> $(document).ready(function() { //elements var progressbox = $("#progressbox"); var progressbar = $("#progressbar"); var statustxt = ...

Populate several input boxes with data derived from a single input field

I am facing an issue with three textboxes in my project. When I type something in the first textbox, the value is sent to state.jsp and displayed using out.println(firsttextboxvalue); on the response ID of the second textbox. However, I want to populate th ...

PHP and JavaScript both offer methods for escaping variables that are written in the syntax ${HOST}

How can I safely handle variables from the database like ${HOST}? This issue arises when code is posted within <pre><code> tags. If left as it is, an error occurs: Uncaught ReferenceError: HOST is not defined. In this specific context, usin ...