Modify a text file in javascript

Hello,

I am creating a save system for my game. I store the data (level stats, high score) in a text file.

Here is the script which creates the file (this is only a test script, the full file will contain the data of 70+ levels):

import System.IO;

var filePath = "data.txt";
var levelID	: String;


function Start()
{
	if (!File.Exists(filePath))
	{
		CreateFile();
	}
}

function CreateFile()
{
	var sw : StreamWriter = new StreamWriter(filePath);
	sw.WriteLine("Modifying the file can cause the loss of your data!!!");
	sw.WriteLine("");
	sw.WriteLine("Level1");
	sw.WriteLine("unlocked");
	sw.WriteLine("000");
	sw.WriteLine("");
	sw.WriteLine("Level2");
	sw.WriteLine("Locked");
	sw.WriteLine("000");
	sw.Flush();
	sw.Close();
	print ("Done");
}

My question is, that how can I update the file when needed? For example, I would like to unlock level 2, and change the high score of level 1.
I know how to search in the file, for example finding the line with Level1. But then how should I modify the line bellow it, and the line below that by 3 lines?
I have heard to rewrite the file, but than I would need a variable which stores the level state, and the high score, right? Because that would be a lot of variable with 70+ levels.

So how should I modify a “select” a specific line, and modify it?

Thanks!

I have only done this in Java. But when I do this in Java I just delete the old file and create a new file with the new context. That might not be the best solution but it might work.
I am not familiar with this in javascript, could you tell me where you found the information that taught you how to go into a text file with javascript?

I have searched the forums, and get the information from the topics. But to rewrite the file, I would need to store the values like the high score in a different variable/level, right?

Yeah I think you should temporarly store them in a different variable.

So I should create variables like

private var levelOneOpen : boolean = true;
private var levelOneScore : int = 0;
private var levelTwoOpen : boolean = false;
private var levelTwoScore : int = 0;
...

Because this would need a lot of variable.

Or do you do it with a different approach?

You could do it that way, Or you could make an array that stores all variables(although that might be more complicated).

I think I will make an array, because I would need 825 private variable in the first way :stuck_out_tongue:
Thanks for your help.

That seems to be a good idea. I’m glad I could help :slight_smile: