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

Viewed 265

Hi and thank you for your help

I have a config.json file that contains this:

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

and I have index.js file that contains:

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

thank you for your help :D

1 Answers

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

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. If you want to have the user instance and the template in different files, you can use a callback function as this:

config.js

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

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

export default config;

index.js

import config from './config.js';

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

Output

Hi Test
Related