簡體   English   中英

Javascript:如何遍歷日志文件

[英]Javascript: How to iterate through log files

我有一個.log文件,它只是名為store_data.log的對象store_data.log

{"name": "Fred", "id": 31323, "favorited": false}
{"name": "Chris", "id": 33123, "favorited": true}
{"name": "Mike", "id": 33223, "favorited": true}

它有一個名為store_data.json的相應文件,其中包含日志文件路徑:

{
    "log_path": "/intua/store_data.log"
} 

在我的JS文件中,我想創建一個獲取路徑並迭代日志信息的函數,但我不知道從哪里開始,因為日志文件不是我知道如何使用的格式。

首先讀取您的文件,用'\\ n'拆分,然后迭代解析它。

const fs = require('fs');
const config = require('store_data.json'); // load config,

const logPath = config.log_path;

(async() => {
    const data = await fs.readFileSync(logPath, 'utf-8');
    const logs = data.split('\n');

    Array.from(logs).forEach(logString => {
        const log = JSON.parse(logString);
        console.log(log); // Your log here.
    })
})();

順便說一句,如果你的日志文件很大,readline或stream會更好。

<script>
var store_data_json_path = '/path/to/store_data.json'; //your store_data.json location

var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', store_data_json_path, false); //this will access the store_data.json data
xmlhttp.send();

var store_data_json = JSON.parse(xmlhttp.responseText);
var store_data_log_path;

store_data_log_path = store_data_json.log_path; //this will retrieve log_path from store_data.json

var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.open('GET', store_data_log_path, false); //this will access the store_data.log data
xmlhttp2.send();

var store_data_log_text = "[" + xmlhttp2.responseText + "]"; //this will add brackets that will make your string a valid json format
store_data_log_text = store_data_log_text.replace(/}/g, "},"); //will replace all } with }, to make it a valid JSON
store_data_log_text = store_data_log_text.replace(/,([^,]*)$/,"$1"); //will remove the last instance of , to make it a valid json

var store_data_log = JSON.parse(store_data_log_text); //we will convert the string to JSON

for(i in store_data_log) { //we will iterate to store_data.log
  console.log(store_data_log[i].name);
  console.log(store_data_log[i].id);
  console.log(store_data_log[i].favorited);
}
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM