0

I have followed many solutions provided in the previous questions but mine is not working. The problem is in .json extension. Whenever I use filename.json, the app will crash with ERR_CONNECTION_RESET but successfully created an empty .json file. However, if I change the extension to filename.txt, the fs.writeFile will successfully create the filename.txt with the data inside and the app will work as expected. Did I miss any configuration here to create the JSON file? Here is the example code I used.

var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}';

// parse json
var jsonObj = JSON.parse(jsonData);
console.log(jsonObj);

// stringify JSON Object
var jsonContent = JSON.stringify(jsonObj);
console.log(jsonContent);

fs.writeFile("./public/output.json", jsonContent, 'utf8', function(err) {
  if (err) {
    console.log("An error occured while writing JSON Object to File.");
    return console.log(err);
  }

  console.log("JSON file has been saved.");
});
8
  • i tested the code you show, it works on my side. Commented Feb 2, 2018 at 6:53
  • 2
    Are you using a live reload server? Because if that's the case, the live-server will track for .json changes and if it finds a new file create event, it'll restart the Node application, hence closing the thread. Commented Feb 2, 2018 at 6:54
  • @Dean Yeah, that's strange! I am not sure what's wrong with my nodejs app. Commented Feb 2, 2018 at 6:55
  • @weirdpanda I am only using nodemon. Could it be the problem? Commented Feb 2, 2018 at 6:59
  • 1
    @striplingboy, yeah! I guess that's the problem. Try excluding --ignore public/**/*.json That should be helpful for debugging. Commented Feb 2, 2018 at 7:00

1 Answer 1

1

So, ERR_CONNECTION_RESET means that the connection was closed midway. My guess, as in the comments, would be that it's a reloading server.

Try using --ignore public/**/*.json and it should work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.