Search code examples
javascriptnode.jsjsonobjectstr-replace

use the filesystem module and the string.replace() to Substitute tokens in a nested object


When I run node index I get undefined. I am trying to use the filesystem module and the string.replace() method to replace tokens in a nested object in collections.js with values from another file (values.json). But when I run the code, nothing changes, and when I console.log finalData, I get undefined. index.js

const fs = require("fs").promises;

async function dataReader(filePath, data) {
  const result = await fs.readFile(filePath);
  try {
    return JSON.parse(result);
  } catch (e) {
    console.error(e);
  }
}

//read values.json
(async () => {
  const value = await dataReader("./values.json");

  //read collection.json
  const data = await dataReader("./collections.json");
  
  //replace tokens in `collection.js` with `values.js`
  let finalData = JSON.stringify(data);
  Object.keys(value).forEach((token) => {
    finalData = finalData.replaceAll(`__${token}__`, value[token])
  });
  
  // write/save the new replaced token values in collection.json
  await fs.writeFile("./collections.json", finalData, (err) => {
    if (err) {
      console.error(err);
    }
  });
});

collection.js

{
  "collection" : [
    {
      "fruit": "__fruit_type__",
    "clothings":{
      "item": "__clothing_type__}"
    }
  },
  {
    "fitness": "__fitness_equipment__",
    "mindfulness": "app called __meditation_app__"
  }
]
}
 
**values.js**
{
    "clothing_type": "winter",
   "fruit_type": "apple",
   "fitness_equipment": "treadmill",
   "meditation_app": "calm"
}

expected result:

The collection file after replacing the tokens will have below content:

{
  "collection": [
    {
      "fruit":"apple",
      "clothings":{
        "item":"winter}"
      }
    },
    {
      "fitness":"treadmill",
      "mindfulness":"app called calm"
    }
  ]
}

Solution

  • Your collection.json is missing some comas and is not well formatted, try to change it to:

    const data = {
      "collection" : [
        {
          "fruit": "__fruit_type__",
        "clothings": {
          "item": "__clothing_type__"
        }
      },
      {
        "fitness": "__fitness_equipment__",
        "mindfulness": "app called __meditation_app__"
      }
    ]
    }
    
    const value = {
        "clothing_type": "winter",
       "fruit_type": "apple",
       "fitness_equipment": "treadmill",
       "meditation_app": "calm"
    }
    
    let finalData = JSON.stringify(data);
      Object.keys(value).forEach((token) => {
        finalData = finalData.replaceAll(`__${token}__`, value[token]);
      });
      
     console.log(JSON.parse(finalData))