1

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.

Tanmay Bairagi
  • 564
  • 5
  • 25

1 Answers1

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.

Joona Yoon
  • 314
  • 3
  • 16
  • But this file contains `export default` also. so it does not define the string as pure json object. And if i use regex even, then i can get the pure dictionary object but how about rewriting this with `export default`? – Tanmay Bairagi Mar 17 '22 at 06:22
  • @TanmayBairagi so how about import/require cluase? as like `import A from 'read_js'` – Joona Yoon Mar 17 '22 at 06:24
  • no. it may not work. i am actually working on vscode plugin and there i need to read multiple files dynamically that are project files used by the user of vscode. – Tanmay Bairagi Mar 17 '22 at 06:45
  • In vscode, there is an API to read file: https://stackoverflow.com/a/38896611/13677554 – Joona Yoon Mar 17 '22 at 06:51