MZ a bit of $dataSystem.gameTitle confusion

hey all

I have run into a bit of an issue with writing a plugin for my game where I can't access the
$dataSystem.gameTitle in the plugin
when I do I get
Code:
Cannot read property 'gameTitle' of null
Spoiler: Code
JavaScript:
    soul.EX.params = PluginManager.parameters(soul.EX.pluginName);
    //var gametitle = soul.EX.params["gameTitle"];
    var gametitle = $dataSystem.gameTitle;
    const fs = require("fs");
    const util = require("util");
    const os = require("os");
    const home = os.homedir();
    const gamefolder = home + "/games/" + gametitle;
    if (fs.existsSync(gamefolder)) {
      console.log("Directory exists!");
    } else {
      console.log("Directory not found.");
      fs.mkdir(gamefolder, { recursive: true }, err => {
        if (err) throw err;
        if (err) console.log(err);
      });
      console.log("Directory Created");
    }
    StorageManager.fileDirectoryPath = function() {
      const path = require("path");
      const base = gamefolder;
      return path.join(base, "save/");
    };
    StorageManager.filePath = function(saveName) {
      const dir = this.fileDirectoryPath();
      return dir + saveName + ".rmmzsave";
    };

I Have confirmed that using params work but when I try to use
JavaScript:
var gametitle = $dataSystem.gameTitle;
instead of
JavaScript:
var gametitle = soul.EX.params["gameTitle"];
, I get an error, what is going on here?
and how do I fix it?
You'll need to wait until the database is loaded before trying to reference it. You can do this by hooking into a function that only runs after the database has been loaded, e.g. the start method of Scene_Boot:
JavaScript:
(() => {
  const alias = Scene_Boot.prototype.start;   // <- store original method
  Scene_Boot.prototype.start = function() {   // <- override
    alias.apply(this, arguments);             // <- invoke original method
    // your code here
  };
})();
The problem is that $dataSystem is null by default. This changes after DataManager.loadDatabase() is called, which happens in Scene_Boot.create(), which happens after Main.onEffekseerLoad() is called, which is probably asynchronous.

In other words, your plugin may call $dataSystem.gameTitle before $dataSystem has been loaded. In programming, you should always assume that "may" will happen. And that's exactly what is happening anyway.

To fix this, you can either override Scene_Boot.start() as @caethyril suggests (overriding DataManager.loadDatabase() works just as well), or alternatively, you can define a getter property like this:
JavaScript:
Object.defineProperty(this, "gametitle", { get: () => $dataSystem.gameTitle });

This way, whenever you call gametitle, it'll be as if you called $dataSystem.gameTitle instead, which will only be evaluated the moment you call gametitle (and hopefully $dataSystem will have been loaded by then).

However, since you're using gametitle immediately afterwards (for gamefolder), you'll still get an error because $dataSystem still hasn't loaded yet.

You could try to make gamefolder a property instead (and get rid of gametitle, or not; it's your choice):
JavaScript:
Object.defineProperty(this, "gamefolder", { get: () => home + "/games/" + $dataSystem.gameTitle });

But again, you're using gamefolder immediately afterwards...

Fortunately, you can move that code into its own function and call that function when needed. In fact, it's better to do that, since there's no guarantee the player (or some rogue application) won't delete your save folder while the game is still running, which could cause the game to crash afterwards, when it tries to access a directory that no longer exists:
JavaScript:
function createGamefolderIfNotExists() {
  if (fs.existsSync(gamefolder)) {
      console.log("Directory exists!");
    } else {
      console.log("Directory not found.");
      fs.mkdir(gamefolder, { recursive: true }, err => {
        if (err) {
          console.log(err);
          throw err;
        }
      });
      console.log("Directory Created");
    }
}
(Note how I only modified your if (err) condition. Once you throw err, console.log(err) will not run!)

And finally, call that function when needed:
JavaScript:
    StorageManager.filePath = function(saveName) {
      createGamefolderIfNotExists();

      const dir = this.fileDirectoryPath();
      return dir + saveName + ".rmmzsave";
    };

By the time StorageManager.filePath() is called, $dataSystem should have already loaded, so calling createGamefolderIfNotExists() should be safe by now.
ok I now no longer get the error but instead of the game title it has created a folder called undefined
ok I now no longer get the error but instead of the game title it has created a folder called undefined

Which solution did you use?

EDIT: Ah, yes. That's the problem I mentioned in my earlier post: You're creating your folder before you even know what it should be called (because $dataSystem hasn't loaded yet).

It's best if you create that folder right before you need it. You never know if someone could've deleted it in the meanwhile, and $dataSystem should be ready by then.
The problem is that $dataSystem is null by default. This changes after DataManager.loadDatabase() is called, which happens in Scene_Boot.create(), which happens after Main.onEffekseerLoad() is called, which is probably asynchronous.

In other words, your plugin may call $dataSystem.gameTitle before $dataSystem has been loaded. In programming, you should always assume that "may" will happen. And that's exactly what is happening anyway.

To fix this, you can either override Scene_Boot.start() as @caethyril suggests (overriding DataManager.loadDatabase() works just as well), or alternatively, you can define a getter property like this:
JavaScript:
Object.defineProperty(this, "gametitle", { get: () => $dataSystem.gameTitle });

This way, whenever you call gametitle, it'll be as if you called $dataSystem.gameTitle instead, which will only be evaluated the moment you call gametitle (and hopefully $dataSystem will have been loaded by then).

However, since you're using gametitle immediately afterwards (for gamefolder), you'll still get an error because $dataSystem still hasn't loaded yet.

You could try to make gamefolder a property instead (and get rid of gametitle, or not; it's your choice):
JavaScript:
Object.defineProperty(this, "gamefolder", { get: () => home + "/games/" + $dataSystem.gameTitle });

But again, you're using gamefolder immediately afterwards...

Fortunately, you can move that code into its own function and call that function when needed. In fact, it's better to do that, since there's no guarantee the player (or some rogue application) won't delete your save folder while the game is still running, which could cause the game to crash afterwards, when it tries to access a directory that no longer exists:
JavaScript:
function createGamefolderIfNotExists() {
  if (fs.existsSync(gamefolder)) {
      console.log("Directory exists!");
    } else {
      console.log("Directory not found.");
      fs.mkdir(gamefolder, { recursive: true }, err => {
        if (err) {
          console.log(err);
          throw err;
        }
      });
      console.log("Directory Created");
    }
}
(Note how I only modified your if (err) condition. Once you throw err, console.log(err) will not run!)

And finally, call that function when needed:
JavaScript:
    StorageManager.filePath = function(saveName) {
      createGamefolderIfNotExists();

      const dir = this.fileDirectoryPath();
      return dir + saveName + ".rmmzsave";
    };

By the time StorageManager.filePath() is called, $dataSystem should have already loaded, so calling createGamefolderIfNotExists() should be safe by now.
thanks it works
now I just need to integrate the log file
JavaScript:
    var logtime = new Date();
    var logFile = fs.createWriteStream(gamefolder + "/" + "log-" + logtime + ".log", {
        flags: "a"
    });
      // Or 'w' to truncate the file every time the process starts.
    var logStdout = process.stdout;
    console.log = function() {
        logFile.write(util.format.apply(null, arguments) + "\n");
        logStdout.write(util.format.apply(null, arguments) + "\n");
    };
    console.error = console.log();
    console.warn = console.log();
where would i put this
@Titanor
The new Date function can create characters that are not accepted in filenames depending on the location and language used by the player's operating system, it would be best to use this to format the date, for example:
YYYY-MM-DD-HH-MM-SS

Maybe this will help:
Read System Time in Game - #5 answer
I have modified the code so it should create a log file called log-02-23-25-33.log yet it does not
what is going on here
now I just need to integrate the log file
JavaScript:
    var logtime = new Date();
    var logFile = fs.createWriteStream(gamefolder + "/" + "log-" + logtime + ".log", {
        flags: "a"
    });
      // Or 'w' to truncate the file every time the process starts.
    var logStdout = process.stdout;
    console.log = function() {
        logFile.write(util.format.apply(null, arguments) + "\n");
        logStdout.write(util.format.apply(null, arguments) + "\n");
    };
    console.error = console.log();
    console.warn = console.log();
where would i put this

You'd put it in the override for Scene_Boot.prototype.start or DataManager.loadDatabase, whichever you think is best.

A few things to note: @Dev_With_Coffee is correct, new Date() may contain characters that are illegal for filenames, such as plus (+), colon (:), and opening and closing parenthesis (( and )).

Also, you're trying to replace console.error and console.warn, which are functions, with console.log(), which is the result of a function (and in this case undefined, since the function is not returning a result). You should use console.error = console.log; and console.warn = console.log; instead (notice that there are no parenthesis this time).
@Titanor
The new Date function can create characters that are not accepted in filenames depending on the location and language used by the player's operating system, it would be best to use this to format the date, for example:
YYYY-MM-DD-HH-MM-SS

Maybe this will help:
Read System Time in Game - #5 answer
You'd put it in the override for Scene_Boot.prototype.start or DataManager.loadDatabase, whichever you think is best.

A few things to note: @Dev_With_Coffee is correct, new Date() may contain characters that are illegal for filenames, such as plus (+), colon (:), and opening and closing parenthesis (( and )).

Also, you're trying to replace console.error and console.warn, which are functions, with console.log(), which is the result of a function (and in this case undefined, since the function is not returning a result). You should use console.error = console.log; and console.warn = console.log; instead (notice that there are no parenthesis this time).
thanks it works now
I made a plugin that uses document.title to create a folder with the game title, in it any character that is not a letter or number or space is removed and as a guarantee, if you prefer, you can replace the spaces with underscores.
If you still need it.

Original thread: https://forums.rpgmakerweb.com/threads/a-bit-of-datasystem-gametitle-confusion.140957/