'How to read and write the content in a JS file

I have a js file that contains some dictionary structure like below example-

File: read_js.js

export default {
  title: 'Backups',
  docTitle: 'Backups',
  navTitle: 'Backups',
  headers: {
    source_name: 'Source Volume (Path)',
    source_type: 'Type',
    source_zone: 'Source Zone',
  }
}

I want to add some data in this dictionary using typescript. How can I achieve this? I tried fs.readFileSync('read_js.js', 'utf8') but this returns all the text present in the file so couldn't read the dictionary and append my own key-value and re-write into the js file.



Solution 1:[1]

It returns value as String: https://nodejs.org/api/fs.html#fsreadfilesyncpath-options

so you can use it after converting to JSON Object with JSON.parse

If you want to export your object and use it, you can import it as it:

https://codesandbox.io/s/holy-frost-7ueevg?file=/src/index.js

for short:

import MyObject from "./a"; // with the name you want

console.log(MyObject); // you can get this

// if you want to "change", you needs to copy and use it for immutability.
const changed = { ...MyObject }; // ES6 spread operator to copy

I have no clue what is your environments, but it works in browser as you can see.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1