Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...