Guide to modifying the storage path for JSON files in NW.js

I am having trouble loading a JSON file from a folder named saveFiles, which is located in the same directory as the nw.exe and package.json files (manifest file). Currently, the program saves the JSON file to the C:\Users\userName\AppData\Local\appName\User Data\Default folder. I have been trying to change the destination folder by adjusting the "chromium-args": "--data-path=''" value in the manifest package.json file. However, I am unsure of what value to use for it to work properly. Here is how my package.json looks like at the moment:

{
"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"
  }
}

Despite trying different variations such as --data-path='./saveFiles/', --data-path='/saveFiles/', --data-path='saveFiles/', I have not been successful in changing the save location. Could my format be incorrect? Is there an alternative way to modify the save location/directory?

Additional Information:

When saving the JSON file, the following code is used:

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');
});

Although this code successfully saves the file to the C:\Users\userName\AppData\Local\appName\User Data\Default folder, the goal is to save it into the saveFiles folder (located alongside the manifest file and nw.exe).

The load function to read the JSON file appears as follows:

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 method loads the file correctly, but currently requires manually placing testSave.json into the saveFiles folder. The aim is to automate the process and save testSave.json directly into the saveFiles folder.

An alternate approach could involve learning how to load the file from the current save location (C:\Users\userName\AppData\Local\appName\User Data\Default), although that remains uncertain to me as well. Ideally, I would prefer to simply change the save location to the saveFiles folder.

Any assistance provided would be greatly appreciated. Thank you.

Answer №1

If you're looking to work with files in Node.js, the 'FS' module is your best friend. I've come up with a handy little function that allows you to input a filename (with extension) and its contents:

const fs = require('fs');

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

To save a file in the root directory of your project, simply use './filename'. Path handling works the same in NW.js as it does in any other node environment. And if you need to save in a directory above your current location, go for '../filename'.

To check your path at any point in your project, just add this snippet:

const path = require('path');

console.log(path);

You can use '../' to move up directories or append additional directories to navigate down.

Both the 'fs' and 'path' modules are native to node.js, so no need for extra npm installs!

Hope this clears things up for you.

EDIT:

If you want to ensure that your file has finished writing before proceeding, listen out for the 'close' event:

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

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

Obtaining JSON information with CakePHP

Is there a way to extract JSON data from the following URL: I am currently working with cakephp 1.3 and looking for solutions on how to accomplish this task. ...

Utilizing Jolt for Json transformation with string concatenation inside an array

String concatenation is needed on the elements in the 7th and 8th positions within an array to create a json message using jolt. Here is a sample spec, input data, actual output, and expected output. Assistance is required for this task while utilizing jol ...

Identifying the class of a clicked button using Jquery

Currently, I am experiencing an issue with my code $(document).ready(function(){ $(".follow-button").click(function(){ alert("asdf"); } }); <button class="follow-button" align="right" align="center"> Follow </butt ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

The issue with the Ajax infinite scrolling gallery is that it repeatedly displays the same images multiple times

I'm currently working on developing a straightforward gallery page that dynamically adds elements as you scroll to the bottom. To achieve this, I am using Django to render an HTML snippet from the backend and then utilizing JavaScript to append it to ...

Looking to transfer JSON data between JavaScript and Java code

I am dealing with a JSON string within my JavaScript code and I want to pass this information to a Java class. Can I simply use a regular Java class for this task or is it necessary to implement a servlet? Furthermore, I am curious about the process of pa ...

Having trouble setting up my Vuex store from localStorage for authentication in Nuxt

I have been working with Nuxt.js and have been trying to create my own authentication system. Everything seems to be functioning correctly, but whenever I refresh the page, the state reverts back to its initial data. To address this issue, I attempted to i ...

Verify if uploading a photo is necessary

Here is my approach to ensuring that a file is added before it can be uploaded: <script type="text/javascript> function check(){ var elm = document.getElementById("hello-world"); if (elm.value.length > 0){ alert("Hey"); re ...

Utilizing JQ to apply various filters within nested arrays

In my JSON data, I have nested arrays for each item I need to collect. Here is a simplified version: [ [ { "Item":"FIRST", "items":[ { "firstitem1":"Item 1", ...

Strategies for temporarily storing values within md-list-item in AngularJS

I am attempting to populate a list with items using material icons. The issue is that the values are being added permanently when the material icon is clicked, disregarding the save and discard buttons at the bottom of the card. My goal is to add values te ...

Using jQuery to select a nested element in HTML

After choosing $("a.tp[programm='" + programm + "']"); I am looking to target the nested element span.thump and update its text content. How can I achieve this? <h4><a programm="74" class="tp" href="#"><img src="/images/tuo.png ...

Transform the value of a string JSON property into a custom object

I'm working with JSON data that I need to deserialize into a C# object. Here is the structure of the data: { "version": 0, "guid": "2166a7d5744d47009adaa29f0e549696", "csv": "one:1,two:2,three: ...

Creating personalized categories with Material-UI's Autocomplete feature in a React application

I've been attempting to customize the groupings in the MUI Autocomplete component, but I haven't had any luck so far. It seems like there is no built-in solution provided by the library (I hope I'm mistaken). https://i.sstatic.net/NcJWU.png ...

The ID of the jQuery droppable element cannot be found

Is there a way to retrieve the ID of a li element from a droppable function? Currently, when I try to do so, it returns undefined. Any suggestions on why this might be happening? The structure of each li element is as follows: <li class="ui-state-def ...

Creating a multi-level mobile navigation menu in WordPress can greatly enhance user experience and make

Hey there, I am currently in the process of developing a custom WordPress theme and working on creating a mobile navigation system. Although I have managed to come up with a solution that I am quite pleased with after multiple attempts, I have encountered ...

Tips for intentionally refreshing or crashing a browser tab by utilizing the response from an AJAX request

Yesterday, we deployed new code to our production environment which included a polling mechanism using setInterval() in Javascript. This feature makes an AJAX request every 15 seconds to update clients with the server. Surprisingly, even though only around ...

Utilizing jQuery to correspond with CSS media queries

Continuing from my previous question about an automatic jQuery image slider, you can refer to it here. I have made some changes in my CSS using media queries and I am trying to incorporate them into my JavaScript code using an 'if / else if' sta ...

Unlocking the Power of Select Options in Vue.js

I am currently learning how to use Vue.js. Below is an example of the Javascript code I have written: new Vue({ el: '#app', data: { classes: [] }, created: function () { var vm = this // Fetch API ...

What is the best way to extract value from subscribing?

I attempted to accomplish this task, however, I am encountering issues. Any assistance you can provide would be greatly appreciated! Thank you! export class OuterClass { let isUrlValid = (url:string) => { let validity:boolean ...

Unable to insert rows into an array using sqlite3 in Node.js

I have a snippet of Node.js code that queries a SQLite Database and prints each row individually. The original code is as follows: var sqlite3=require('sqlite3').verbose(); var db=new sqlite3.Database('./database.db',(err)=>{ i ...