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";
1
  • 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: stackoverflow.com/questions/3665115/… Commented Nov 11, 2021 at 8:20

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

@Adian Arif Zakaria, any idea about how can we do the same in React.js or Angular js because fs doesn't work client side
@JagannathSwarnkar I've updated my code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.