简体   繁体   English

如何通过节点 js 中的变量自动替换 config.json 文件中的文本

[英]How can I replace text from a config.json file automatically by a variable in node js

Hi and thank you for your help嗨,谢谢你的帮助

I have a config.json file that contains this:我有一个 config.json 文件,其中包含:

{
    "test": {
        "hi": {
            "text": "Hi ${user.name}"
        }
    }
}

and I have index.js file that contains:我有 index.js 文件,其中包含:

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

var user = {name: "Test", tag: "#1234")

console.log(`${config.test.hi.text}`) // Output: "Hi ${user.name}"
                                      // Expected output: Hi Test

I want when you change in the config.json the user.name to something like user.tag its automatically replaces him without .replace() function我希望当您在 config.json 中将user.name更改为user.tag之类的东西时,它会自动替换他而无需.replace() function

thank you for your help:D谢谢你的帮助:D

When using Template literals, the expressions in the placeholders and the text between the backticks (` `) get passed to a function that concatenates the strings into a single string, replacing the values inside $(variable) .使用模板文字时,占位符中的表达式和反引号 (` `) 之间的文本被传递给 function ,它将字符串连接成单个字符串,替换$(variable)中的值。 This process happens at the time you define the template and cannot be resolved later as you do in your code.此过程在您定义模板时发生,以后无法像您在代码中那样解决。 Refer to the documentation: Template literals请参阅文档: 模板文字

It would be also a bad coding practise as if the user variable didn't exist in the index.js file it wouldn't give you a compile error, but a nasty runtime error.这也是一种不好的编码习惯,就好像用户变量不存在于index.js文件中一样,它不会给您一个编译错误,而是一个令人讨厌的运行时错误。

The only way to do it is to have your template literal in reach of your variable scope, that means that the template literal can read the variable at the moment it's executed.做到这一点的唯一方法是让您的模板文字可以访问您的变量 scope,这意味着模板文字可以在执行时读取变量。 If you want to have the user instance and the template in different files, you can use a callback function as this:如果要将用户实例和模板放在不同的文件中,可以使用回调 function,如下所示:

config.js配置.js

const callback = (user) => {
    return `Hi ${user.name}`
}

const config = {
    callback,
    anotherConfig: {
        hi: {
            example: "This is another config"
        }
    }
}

export default config;

index.js index.js

import config from './config.js';

const user = {name: "Test", tag: "#1234"};
console.log(config.callback(user))

Output Output

Hi Test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM