Search code examples
javascriptjquerynode.jsnode-webkitnwjs

NW.js: If both arrays are equal not working


I'm working on an IDE as a side project using NW.js and I need to detect if there's any changes to my project tree when focused.

I'm using JQuery's .each check if the files in the project folder have changed since being focused.

Here's what I have for window focused function.

win.on("focus", function() {
  var stringArray = [];
  listFiles = fs.readdirSync(__dirname + "/content/project");
  console.log("checking if there's any changes");
  $.each($("[data-nme]"), function() {
    stringArray.push(this.textContent);
  });
  var array1 = listFiles;
  var array2 = JSON.stringify(stringArray);

  console.log(array1);
  console.log(array2);

  if (array1.toString() != array2.toString()) {
    console.log("there's been a change");
  }
});

When I debug I get the following result.

enter image description here

I don't understand why it says there's a difference with the array when it's the exact same.

if (array1.toString() != array2.toString()) {
  console.log("there's been a change");
}

Solution

  • The error is in the way you check equality. One of the array is JSON.stringified the other is not. Don't use JSON.stringify(stringArray) for defining array2.

    var foo = ["bar"];
    foo.toString();
    

    Outputs : "foo"

    JSON.stringify(foo).toString()
    

    Outputs : "["foo"]"

    This condition should be working (haven't tested) :

     if (array1.toString() != stringArray.toString()) {
        console.log("there's been a change");
      }
    

    if you want the best option to compare arrays check this one : How to compare arrays in JavaScript?