Search code examples
javascriptrequire

error - require is not defined . How to write a json file with the help of javascript


I want to make a level editor for my platformer game with phaser and I am saving the data in json files. I want to write json with javascript and I searched then i came to know that we can write it first writing this const fs = require("fs") and many more but on this line I get error require is not defined. I want to create a json file. I using it in the browser with windows 7. how can I use require to do so.

If there is any other way to write json file with js, then please tell.


Solution

  • require doesn't exist on the browser/client side. Also, you cannot use fs as well, it should be implemented on the back-end side. Please use the following approach -

    function download(filename, json) {
      var element = document.createElement('a');
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + JSON.stringify(json));
      element.setAttribute('download', filename);
    
      element.style.display = 'none';
      document.body.appendChild(element);
    
      element.click();
    
      document.body.removeChild(element);
    }