T Snake
T Snake

Reputation: 89

Getting text from a .txt file in a variable

So I have this html file with some A-frame Code (It just adds a ball to the scene). And a .js script which contains functions that can move the ball, like moveUp();. Now I want to be able to execute some JavaScript code (that uses the move fuctions) written in a .txt file using the eval of JavaScript.

But client side JavaScript can't read or write a .txt file (I don't want to choose the file myself at runtime). Is there a way to get the data of a .txt file in a JavaScript var without having to set up a server and using server side JavaScript?

Upvotes: 0

Views: 201

Answers (1)

Andy
Andy

Reputation: 63524

I'll make a recommendation as to how you might proceed. It sounds like what you really need is a way of allowing a user to save commands, rather than actual code, to a file, and then allow those commands to be loaded again and to influence the position etc of the shape on the screen.

Let's say you have a move function that takes in object, x and y arguments:

function move(obj, x, y) {
  // Move obj using x and y coords
}

Maybe you have a form that allows the user to input those coords, but somehow you want to save those coords along with the action (move).

The simplest way of doing that is to use an array of objects. The advantageof this is you can then stringify into JSON, save that data, and reload it and parse it back to your application to your heart's content.

For example you might save your data as a series of commands in an array like this:

const commands = [
  { action: 'move', x: 30, y: 50 },
  { action: 'move', x: 300, y: 510 }
];

You can add more command objects by pushing them on to the array.

Then you might have an object containing some action functions. Let's use move again:

const commandFns = {
  move: function (obj, x, y) {
    // Move obj using x and y coords
  }
}

So to move the fire off the commands you just iterate over the actions array, calling the appropriate function.

const obj = currentShapeToBeMoved;
commands.forEach(({ action, x, y }) => actionFns[action](obj, x, y));

To save the commands you JSON.stringify(commands) the commands data object. Maybe save that to a file to disk, or perhaps even better, localStorage.

To load the file back into the application, find where you've saved the data and then JSON.parse(data) back into its array form.

In short, you don't append anything to the file. All you're doing is loading data, updating the the data in your application, then saving the same/amended data back.

Upvotes: 2

Related Questions