【问题标题】:change value in imported file, use new value in script更改导入文件中的值,在脚本中使用新值
【发布时间】:2021-07-07 00:19:37
【问题描述】:

如何更改导入的 json 文件中的值并在脚本中使用新更改的值? 这是我正在尝试使用的东西,但它会让我在值实际上也被计为它被更改的值之前重新启动程序。

const prompt = require('prompt-sync')()
const exit = require('exit')
var config = require('.\\config.json')
const debug = config['debug']
const fs = require('fs-extra')


function wait(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms)
    })
}
// if (debug == "true") {console.log()}
if (debug == "true") {
    var debug_on = prompt("debug mode is on, would you like to turn it off? ")
    if (debug_on == "yes") {
        console.log("debug has been disabled")
        require('child_process').execSync('node config_setter.js --debug=false')
    }
    if (debug_on == "no") {
        console.log("debug will stay enabled")
    }
}

if (config['experimental-asked'] == "false") {
    var exp_clean = prompt("do you want to try experimental cleaning? ")
    if (exp_clean == "yes") {
        require('child_process').execSync('node config_setter.js --clean=true --asked=true')
    }
    if (exp_clean == "no") {
        console.log("as you wish")
        require('child_process').execSync('node config_setter.js --clean=false --asked=true')
    }
    if (exp_clean == "debug") {
        console.log("debug enabled, this enables cleaning also")
        require('child_process').execSync('node config_setter.js --clean=true --asked=true --debug=true')
    }  
}
if (debug_arg !== undefined) {
        if (exp_asked !== undefined) {
            config['experimental-cleaning'] = exp_clean
            config['experimental-asked'] = exp_asked
            config['debug'] = debug_arg
            config_string = JSON.stringify(config, null, 4)
            fs.writeFile(config_dir, config_string, (err) => {
                if (err) {console.log("error"), err}
            })
            exit
        }
}

【问题讨论】:

  • 哪个值?尝试仅导入、记录、更改然后再次记录的几行代码怎么样?在这里发布?
  • 您使用的是什么操作系统? Mac、Windows 等?
  • 我在 Windows 上,我正在尝试更改配置['experimental-cleaning']
  • 在 windows 上的语法应该是 var config = require("./config")

标签: javascript node.js config fs


【解决方案1】:

您当前正在以字符串形式读取文件

var config = require('.\\config.json')

您需要将其转换为 JSON 以便根据您的第二个 sn-p 使用它:

var config = require('.\\config.json');
var configJSON = JSON.parse(config);

【讨论】:

  • 我调用第二个 sn-p 并用它更改值,而第一个 sn-p 在第二个进程退出后转到另一个块,因此我可以在 if 语句中使用新值 true第一个 sn-p, false, 1> 2, true > new if (var == true) {}
  • 第二个 sn-p 也以同样的方式获取配置 const config = require('.\\config.json')
  • @Fisheiyy 我明白了,在这种情况下你仍然需要解析配置文件。
猜你喜欢
  • 2023-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-25
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
相关资源
最近更新 更多