How to save the output of a console.log(object) to a file?

后端 未结 9 1289
情深已故
情深已故 2020-11-28 00:14

I tried using JSON.stringify(object), but it doesn\'t go down on the whole structure and hierarchy.

On the other hand console.log(object) d

9条回答
  •  死守一世寂寞
    2020-11-28 00:48

    Update: You can now just right click

    Right click > Save as in the Console panel to save the logged messages to a file.

    Original Answer:

    You can use this devtools snippet shown below to create a console.save method. It creates a FileBlob from the input, and then automatically downloads it.

    (function(console){
    
    console.save = function(data, filename){
    
        if(!data) {
            console.error('Console.save: No data')
            return;
        }
    
        if(!filename) filename = 'console.json'
    
        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }
    
        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')
    
        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
     }
    })(console)
    

    Source: http://bgrins.github.io/devtools-snippets/#console-save

提交回复
热议问题