Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/65859720/error-require-is-not-defined-how-to-write-a-json-file-with-the-help-of-javas

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...