[英]How to store console.log data to file?
我有對象樹:
let tree = {id: 1, children: [{id: 2, children: [{id: 3}]}]}
我想將此樹中的所有id
存儲在帶有子元素的選項卡的文件中:
1
2
3
我使用這個 function 來顯示樹的元素:
show(tag: XMLtag) {
console.log(tag.show());
if (tag.getChildren().length == 0) {
return;
}
tag.getChildren().forEach((c) => {
this.show(c);
});
}
這個 function 給了我:
1
2
3
是否可以將結果寫入文本文件或顯示在帶有格式的瀏覽器頁面上?
修改固有的console.log
function:
var file = ''
console.log = (text) => {
file += text + '\n';
}
// 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(link);
link.click();
link.remove();
}
const log = console.log
console.log = (logData) => {
// append log to a file, something like this
fs.appendFileSync('logs.txt', logData + '\n');
// preserve original logging functionality
log(logData)
}
當只有一個參數傳遞給 console.log 時,這將起作用。
您可以在頁面上的pre
元素內顯示格式化文本。
const pre = document.querySelector('pre'); function addToDisplay(text) { pre.innerText += text + '\n'; } addToDisplay('first line'); addToDisplay(' second line');
<pre></pre>
然后在show()
function 中添加一行:
// add `indent` parameter to indent children
show(tag: XMLtag, indent = "") {
console.log(tag.show());
// add this to display indented items in browser:
addToDisplay(indent + tag.show());
if (tag.getChildren().length == 0) {
return;
}
tag.getChildren().forEach((c) => {
// indent children by an additional 2 spaces
this.show(c, indent + " ");
});
}
您可能想要使用 node.js 文件系統庫。 簽出 fs.writeFile或fs.writeFileSync
const { writeFileSync } = require('fs')
writeFileSync('some-file.json', JSON.stringify({ id: 1, data: [{ id: 2 }, { id: 3 }] }, null, 2))
在同一目錄中查找some-file.json
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.