Medicale
Medicale

Reputation: 1

What's a better way to write data to JSON files?

So I wrote a script to save data from my project into JSON files, but I've been told it's clunky. I essentially just wrote three nearly-identical writeFile methods as such:

var fs = require('fs');
fs.writeFile('public/game-data.json', JSON.stringify(getGameData()), (e: any) => {
    if(e){
        console.error(e);
        return;
    };
    console.log("Saved game data to game-data.json.");
});

fs.writeFile('public/shop-items.json', JSON.stringify(getShopData()), (e: any) => {
    if(e){
        console.error(e);
        return;
    };
    console.log("Saved shop data to shop-data.json.");
});

fs.writeFile('public/hash.json', JSON.stringify(getHashData()), (e: any) => {
    if(e){
        console.error(e);
        return;
    };
    console.log("Saved hash data to hash.json.");
});

I was recommended to use a loop and a "trustable function" (can't find the definition of that anywhere)... Anybody have any recommendations?

Upvotes: 0

Views: 63

Answers (2)

Ben Stephens
Ben Stephens

Reputation: 3371

A slightly different approach (not tested and I don't know Typescript, so that might be a bit dodgy):

var fs = require('fs');

const console_callback = (message: string) => (e: any) =>
    e ? console.error(e) : console.log(message);

fs.writeFile(
    'public/game-data.json',
    JSON.stringify(getGameData()),
    console_callback("Saved game data to game-data.json.")
);

Upvotes: 0

imvain2
imvain2

Reputation: 15857

The only thing I can think of is this:

var fs = require('fs');

function saveJSON(file, data, type) {
  fs.writeFile(file, JSON.stringify(data), (e: any) => {
    if (e) {
      console.error(e);
      return;
    };
    console.log("Saved " + type + " data to " + file);
  });
}

saveJSON('public/game-data.json', getGameData(), 'game');

Upvotes: 2

Related Questions