0

I'm trying to change a value within a config and then use that new value later?

// CONFIG.JSON
// BEFORE CHANGE
{
    "value": "baz"
}
// AFTER CHANGE
{
    "value": "foobar"
}

// MAIN JS ILE
const config = require('config.json')

function changeValue() {
    config['value'] = "foobar"
    var config_string = JSON.stringify(config, null, 4)
    fs.writeFile(config_dir, config_string, (err) => {
        if (err) {console.log("error", err)}
    })
}

function useValue() {
    console.log(config['value'])
    // output will be "baz"
    // fs.writeFile does not change the file data until the end of the whole script
    // which is why I need help, how can I change a value and use it if ^^^
}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Fisheiyy
  • 65
  • 6

2 Answers2

1

You can use fs.writeFileSync instead which is synchronous and blocking, this means that your other code won't run until the file has finished being written.

// CONFIG.JSON
// BEFORE CHANGE
{
    "value": "baz"
}
// AFTER CHANGE
{
    "value": "foobar"
}

// MAIN JS ILE
const config = require('config.json')

function changeValue() {
    config['value'] = "foobar"
    var config_string = JSON.stringify(config, null, 4)
    fs.writeFileSync(config_dir, config_string)
    // Will wait until the file is fully written, before moving on
}

function useValue() {
    console.log(config['value'])
}
lejlun
  • 4,140
  • 2
  • 15
  • 31
  • Just a reminder: when writing Javascript, one should generally prefer "asynchronous" over "synchronous" code whenever possible. – paulsm4 Aug 03 '21 at 19:49
1

Easy - just assign a callback.

For example:

https://www.geeksforgeeks.org/node-js-fs-writefile-method/

const fs = require('fs');
  
let data = "This is a file containing a collection of books.";
  
fs.writeFile("books.txt", data, (err) => {
  if (err)
    console.log(err);
  else {
    console.log("File written successfully\n");
    console.log("The written has the following contents:");
    console.log(fs.readFileSync("books.txt", "utf8"));
  }
});

In your case, perhaps something like:

function changeValue() {
    config['value'] = "foobar"
    var config_string = JSON.stringify(config, null, 4)
    fs.writeFile(config_dir, config_string, (err) => {
        if (!err) {
          // UseValue stuff...
        } else {
          console.log("error", err)}
        }
    })
}

Here's another example:

fs.writeFile() doesn't return callback

paulsm4
  • 114,292
  • 17
  • 138
  • 190