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



我试图改变配置中的值,然后使用新值以后?

// 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 successfullyn");
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()没有't返回回调

最新更新