Node-fs-extra: append to json file when using fs.writeJson()

Created on 15 Jan 2018  路  2Comments  路  Source: jprichardson/node-fs-extra

  • Operating System: Ubuntu 16.4 lts
  • Node.js version: 8.9.4
  • fs-extra version: 0.30.0

is there any to change an object within object without deleting the other objects in the json file ?

question

Most helpful comment

@BlackGhost3 You need to read the file first and merge the data before writing if you don't want to overwrite the old data.

All 2 comments

@BlackGhost3 You need to read the file first and merge the data before writing if you don't want to overwrite the old data.

@BlackGhost3 using FS-extra you can still use FS.
You can create a pseudo-JSON without having to read and merge each time.

const fs = require('fs-extra');
Object.prototype.print_to_pseudoJSON = function (type_of_operation, objJSON) {
    switch (type_of_operation) {
        case "Overwrite":
            if (fs.existsSync(this.valueOf())) {
                fs.removeSync(this.valueOf());
            }
            fs.ensureFileSync(this.valueOf());
            fs.appendFileSync(this.valueOf(), new String(JSON.stringify(objJSON) + ",\n"));
            break;
        case "Append":
            fs.ensureFileSync(this.valueOf());
            fs.appendFileSync(this.valueOf(), new String(JSON.stringify(objJSON) + ",\n"));
            break;
    }
}
Object.prototype.read_pseudoJSON = function () {
    let charSequence = fs.readFileSync(this.valueOf(), "utf8");
    return JSON.parse(["[", charSequence.slice(0, -2), "]"].join(""));
}

this is not a great solution, but working with several hundred megabyte in file JSON, so far I have not invented anything beter. I know the topic is closed, but I wanted to help, considering that the last answer is not cool.

Was this page helpful?
0 / 5 - 0 ratings