Search code examples
javascripttextjavascript-objects

Print javascript object to txt file


I have a javascript object like this

    var data = {
    "person": {
        "name": "John Doe",
        "address": "N.Y City",
        "city": "N.Y",
        "country": "USA",
        "phone": "Ph: 12345"
  }

I want to print it like this: Person.Name----Person.Address----Person.Phone in a txt file. Until now I am able to do so with console.log like this

console.log(data['person']['name'] + "----" + data['person']['address'] + "----" + data['person']['phone'])

And the output in console is: "John Doe ---- N.Y City ---- Ph: 12345"

I don't want to print all the values of the json. I want to print some of these and also I want to have this between them "----".

Is it possible to print this in a txt file? I haven't fine anything yet.


Solution

  • In the Node.js context, you can do it this way:

    const fs = require('fs');
    const yourObject = {
     // ...addProperties here.
    }
    
    fs.writeFile("/path/to/save.txt", JSON.stringify(yourObject), 'utf8', function (err) {
        if (err) {
            return console.log(err);
        }
    
        console.log("The file was saved!");
    }); 
    

    or with async version writeFileSync()

    fs.writeFileSync("/path/to/save.txt", JSON.stringify(yourObject), 'utf8')
    

    In the Browser Context You can do this:

    // Function to download data to a file
    function download(data, filename, type) {
        var file = new Blob([data], {type: type});
        if (window.navigator.msSaveOrOpenBlob) // IE10+
            window.navigator.msSaveOrOpenBlob(file, filename);
        else { // Others
            var a = document.createElement("a"),
                    url = URL.createObjectURL(file);
            a.href = url;
            a.download = filename;
            document.body.appendChild(a);
            a.click();
            setTimeout(function() {
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);  
            }, 0); 
        }
    }
    

    after declaring that function, do this:

    download(JSON.stringify(yourObject), 'file', 'txt') // file is filename, and txt is type of file.