Search code examples
javascriptjsonnw.js

How to change JSON save location/directory in NW.js


I want to load a JSON file from a folder called saveFiles (in the same directory as the nw.exe file and the package.json file (manifest file)). The problem is that the program currently saves the JSON file to the C:\Users\userName\AppData\Local\appName\User Data\Default folder. I cannot figure out how to change the destination folder. I read that I could change it by adjusting the "chromium-args": "--data-path='' value in the manifest package.json file. But I do not know what value I need to use for it to work. Currently the package.json looks like this:

{
"main": "index.html",
"name": "appName",
"chromium-args": "--data-path='./saveFiles/'",
"window":
  {
      "toolbar": true,
      "width": 1600,
      "height": 900,
      "min_width": 1000,
      "min_height": 500,
      "fullscreen": true,
      "title":"App Name"
  }
}

I have tried several variations to try to make it work: --data-path='./saveFiles/', --data-path='/saveFiles/', --data-path='saveFiles/', but nothing has been successful. Is my format wrong? Should I be using something other than "chromium-args": "--data-path=''"? Is there a different way to change the save location/directory? I do not know how to change it to make it work.

More information:

When I save the JSON file, I use the following code:

var fs = require('fs');
var path = require('path');
function saveSettings (settings, callback) {
  var file = 'testSave.json';
  var filePath = path.join(nw.App.dataPath, file);
  fs.writeFile(filePath, settings, function (err) {
    if (err) {
      console.info("There was an error attempting to save your data.");
      console.warn(err.message);
      return;
    } else if (callback) {
      callback();
    }
  });
}
var mySettings = {
  color:'red',
  secondaryColor:'blue'
}
mySettings = JSON.stringify(mySettings);
saveSettings(mySettings, function () {
    console.log('Settings saved');
});

This works to save the file to the C:\Users\userName\AppData\Local\appName\User Data\Default folder, but I want to save it to the saveFiles folder (in the same location as the manifest file (package.JSON) and nw.exe file (which is in the same folder as the package.json)).

The load function to load the JSON file looks like this:

function testLoadFunc(){
  path = require('path');

  var xmlhttp = new XMLHttpRequest();
  var url = "saveFiles/testSave.json";

  xmlhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
        var loadedSettings = JSON.parse(this.responseText);
        console.log('color: ' + loadedSettings.color);
      }
  };
  xmlhttp.open("GET", url, true);
  xmlhttp.send();
}
testLoadFunc(); //Loads json file

This loads the file correctly, but I have to manually place the testSave.json file into the saveFiles folder. I want to automatically save the testSave.json into the saveFiles folder. Thus I am trying to find out how to change the save location/directory.

An alternative option would be to figure out how to load the file from the current save location C:\Users\userName\AppData\Local\appName\User Data\Default, but I do not know how to do that either. The preferable option would be to just change the save location to the saveFiles folder.

Thank you for any help you can provide.


Solution

  • One thing you can do is use the 'FS' module which is included with node. I've written a function that should allow you to pass in a filename (including extension) and fileContents:

    const fs = require('fs');
    
    function writeToFileNWJS(outfilePath, contents){
        let outfile = fs.createWriteStream(outfilePath);
        outfile.write(contents);
        outfile.end();
    }

    If you wanted to save a file in the root directory of your project, use './filename' as your filename. Path relativity is the same in NW.js as it is anywhere else in node. If you want to save in the directory above where you are at, use '../filename'.

    If you want to see what your path is anywhere in your project, add this to the file:

    const path = require('path');
    
    console.log(path);

    You can concat '../' to the beginning your path for each directory you want to climb up; or concat additional directories to the end of your path to drill down.

    Both the 'fs' and 'path' modules are included with node.js and should not require any additional npm install commands.

    Hope this helps!

    EDIT:

    If you want to ensure your file is completely written before calling another function, you can call another function when the 'close' event is fired:

    outfile.on('close', function() {
      console.log('file done');
    });