0

I have a json object like this

{
   APP_NAME: "Test App",
   APP_TITLE: "Hello World"
}

Now I want to convert this into a javascript file and download that file the file format should be like this

// config.ts

export const APP_NAME: "Test App";
export const APP_TITLE: "Hello World";
Jagannath Swarnkar
  • 339
  • 1
  • 3
  • 9
  • Browsers don't have local file access, so if you're running this as JavaScript in your browser you won't be able to put the file in a particular location. If you just want to have the browser download the file and put it into the download directory for your system, you can use this SO answer to download a string as a file: https://stackoverflow.com/questions/3665115/how-to-create-a-file-in-memory-for-user-to-download-but-not-through-server – Joseph Nov 11 '21 at 08:20

1 Answers1

3

For this case, you can use fs.createWriteStream() to write the data into a file. Loop the json object and append the content.

Option 1: Backend-side

// Initialize the file
var fs = require('fs')
var editor = fs.createWriteStream('config.ts')

const data = {
    APP_NAME: "Test App",
    APP_TITLE: "Hello World"
};

// Loop every keys
Object.keys(data).forEach((key) => {
    // Append the text into the content
    editor.write(`export const ${key}: "${data[key]}";\n`)
});

// Save everything and create file
editor.end()

Option 2: Frontend-side

<html>
    <script>
        const data = {
            APP_NAME: "Test App",
            APP_TITLE: "Hello World"
        };

        let content = '';
        Object.keys(data).forEach((key) => {
            // Append the text into the content
            content += `export const ${key}: "${data[key]}";\n`;
        });

        let a = document.createElement('a');
        a.href = "data:application/octet-stream,"+encodeURIComponent(content);
        a.download = 'config.ts';
        a.click();
    </script>
</html>
Adlan Arif Zakaria
  • 1,706
  • 1
  • 8
  • 13