George Reason
George Reason

Reputation: 173

How to write to a JSON file in Node

I am currently requiring a JSON file which I am reading data from.

var allUORHours = require('./UORHoursAch.json');

How do I then write to the file? The below doesn't make any changes to the file

allUORHours.test = {};

Upvotes: 1

Views: 175

Answers (2)

Kim Honoridez
Kim Honoridez

Reputation: 997

You may use the File System API's writeFile():

https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback

Upvotes: 2

Amadan
Amadan

Reputation: 198304

No, of course it doesn't. It just changes the variable's value. To write a JSON, you would need to convert to JSON, then write to a file:

var fs = require('fs');
fs.writeFile('./UORHoursAch.json', JSON.stringify(allUORHours), function (err) {
  if (err) {
    console.log(err);
  } else {
    console.log("Saved");
  }
});

Upvotes: 0

Related Questions