如何在所需文件中使用新写入的值?

How can I use a newly written value in a required file?

我正在尝试更改配置中的值,然后在稍后使用该新值?

// 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 ^^^
}

您可以使用同步和阻塞的 fs.writeFileSync,这意味着您的其他代码不会 运行 直到文件完成写入。

// 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'])
}

简单 - 只需分配一个回调。

例如:

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

在你的情况下,可能是这样的:

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

这是另一个例子: