0

I have an automated script (made in Node.js + TS) that creates some files automatically and replaces some template content depending on the user input.

The thing is, I need to append data to a file after a specific content, but keeping its structure as it is a JS object file.

The file content is something similar to this:

export const myConst = {
  abc: {
    propA: {
      contentA: 'something',
      contentB: getMyContent('something').url,
    },
    propB: {
      contentC: 'another content',
      contentD: 'another url',
    }
  },
  def: {
    propC: {
      contentE: 'loremipsum',
      contentF: getMyContent('lorem').name,
    },
  }
}

What I'd like to do is to introduce a new structure inside one of the already defined properties without messing with the original structure. For example, I'd like to append a new property inside abc property, so that the result looks like this:

...
  abc: {
    propA: {
      contentA: 'something',
      contentB: getMyContent('something').url,
    },
    newProp: {
      myNewProp: getMyContent('newProp').url,
    },
    propB: {
      contentC: 'another content',
      contentD: 'another url',
    },
  },
...

I've thought of finding the contents of the file (i.e.: propA: {) and then append in a new line, but two properties with the same name might exist at different levels, so that would be innacurate and prone to errors.

Also, I can't save this as a JSON, parse it, modify it and re-write it, since it has calls to some helper functions on the file, as you can see with getMyContent.

Is there any way to append content into a file defining object properties after a specific property without messing with the object structure?

I'm using fs-extra library for all the file modifications.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Unapedra
  • 2,043
  • 4
  • 25
  • 42

0 Answers0