Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

javascript - How to store console.log data to file?

I have tree of objects:

let tree = {id: 1, children: [{id: 2, children: [{id: 3}]}]}

I want to store all id in this tree in file with tab for elements that have children:

1
  2
    3

I use this function to show elements of tree:

show(tag: XMLtag) {
    console.log(tag.show());

    if (tag.getChildren().length == 0) {
        return;
    }

    tag.getChildren().forEach((c) => {
        this.show(c);
    });
}

This function gives me:

1
2
3

Is it possible to write result to text file or display on the browser page with formatting?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Modify the inherent console.log function:

var file = ''
console.log = (text) => {
    file += text + '
';
}
// Call save() to save the file, you can do this onbeforeunload if you want or call it manually from console.

function save() {
    var link = document.createElement('a');
    link.href = 'data:text/plain;charset=UTF-8,' + encodeURIComponent(file);
    link.innerHTML = 'download';
    link.download = 'Console_log.txt';     
    document.body.appendChild(file);
    link.click();
    link.remove();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...