【问题标题】:How can I use a newly written value in a required file?如何在所需文件中使用新写入的值?
【发布时间】:2021-11-04 21:03:42
【问题描述】:

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

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

【问题讨论】:

    标签: javascript node.js fs


    【解决方案1】:

    您可以使用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'])
    }
    

    【讨论】:

    • 提醒一下:在编写 Javascript 时,通常应该尽可能选择“异步”而不是“同步”代码。
    【解决方案2】:

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

    例如:

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

    这是另一个例子:

    fs.writeFile() doesn't return callback

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2016-12-31
      • 2021-12-24
      相关资源
      最近更新 更多