0

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?

4
  • 3
    You should go back to the person who told you that and ask them. Commented Oct 23, 2020 at 20:03
  • 1
    Create a function that accepts data and fileName, then refactor all three functions to be calls like myWritFile(getGameData(), 'game-data.json')? Commented Oct 23, 2020 at 20:05
  • 1
    Imagine writing a function, writeData, that you called like this: writeData('game', 'game-data.json', getGameData()), then writeData('shop', 'shop-items.json', getShopData()), and again for hash. How would you go about writing it? Commented Oct 23, 2020 at 20:07
  • I wouldn't say clunky. Its repetitive, but not clunky. I looked for trustable function as I'm always looking to learn new things and I can't find any explanation either. Commented Oct 23, 2020 at 20:13

2 Answers 2

2

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');
Sign up to request clarification or add additional context in comments.

2 Comments

I'd suggest one more parameter for the log output, which might be passed "game", "shop", or "hash"
This is an awesome solution, thank you!! I'm new to programming and still getting used to the logic.
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.