简体   繁体   中英

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 = {};

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM