123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430 |
- const fs = require('fs');
- const path = require('path');
- const {logger} = require("./logger");
- const {rustConfig} = require("../config");
- const http = require("./http");
- const readline = require('readline');
- function checkPathSync(filePath) {
-
- const directoryPath = path.resolve(filePath);
-
- if (!fs.existsSync(directoryPath)) {
-
- logger.info('目录不存在,正在创建...');
- try {
-
- fs.mkdirSync(directoryPath, {recursive: true});
- logger.info('目录已成功创建');
- } catch (error) {
-
- logger.error('创建目录失败:', error);
- return false
- }
- } else {
-
-
- }
- return true
- }
- function checkFilePath(filePath) {
-
- const directoryPath = path.resolve(filePath);
- if (fs.existsSync(directoryPath)) {
- logger.info('文件存在:' + filePath);
- return true
- } else {
- logger.error('文件不存在:' + filePath);
- return false
- }
- }
- function writeFile(filePath, text, breakFun) {
- fs.writeFile(filePath, text, (err) => {
- if (err) {
- logger.error('写入文件时发生错误:', err);
- breakFun(err)
- } else {
- logger.log('文件已成功写入!');
- breakFun(null, true)
- }
- });
- }
- function copyFileSync(source, destination) {
- try {
-
- fs.copyFileSync(source, destination);
-
- return true;
- } catch (err) {
- return false;
-
- }
- }
- function dowFile(url, fileName, dowPath, headers) {
- return http.dowFile(url, fileName, dowPath, headers)
- }
- function delFile() {
- }
- function getLastFile(dirPath, number, callback) {
- fs.readdir(dirPath, async (err, files) => {
-
- if (err) {
- logger.error(`无法列出目录。`, err);
-
- } else {
- let fileList = [];
-
-
- for (file of files) {
- const filePath = path.join(dirPath, file);
-
- const stats = await fs.promises.stat(filePath);
- if (stats.isFile()) {
- fileList.push({name: file, time: stats.birthtime.getTime()});
- logger.info("----------------所有文件:" + filePath + "时间:" + stats.birthtime.getTime())
- }
- }
- fileList.sort((a, b) => b.time - a.time);
- for (a of fileList) {
- const filePath = path.join(dirPath, a.name);
- logger.info("排序之后的顺序:" + filePath + "\ttime:" + a.time)
- }
- let lastFileList = fileList.slice(0, number != -1 ? number : fileList.length);
- let lastFileNameList = lastFileList.map((item) => item.name);
- callback(lastFileNameList.reverse(), lastFileList.reverse());
- }
- });
- }
- async function readLastNLines(dirPath, filePathList, n) {
- try {
- const fileList = [];
- var count = 0;
- for (var i = filePathList.length - 1; i >= 0; i--) {
- var item = filePathList[i];
- const filepath = `${dirPath}/${item}`;
- logger.info("日志文件:" + filepath)
-
-
-
-
- const lines = await readLinesFromEnd(filepath, n - count);
-
- fileList.push({
- filePath: item,
- lines: lines,
- })
- count += lines.length;
- if (count >= n) {
- break
- }
- }
- fileList.reverse();
- const allFile = [].concat(...fileList.map((item) => item.lines));
- const lastNLines = allFile.slice(-n).reverse();
- return lastNLines;
- } catch (e) {
- logger.info('读取文件发生异常咯~~2', e);
- }
- }
- async function getRecentLogs(dirPath, logFiles, requiredLogs = 100) {
- let logs = [];
- try {
- let logsSize = requiredLogs
- for (const file of logFiles) {
- let log = [];
-
- const filepath = `${dirPath}/${file}`;
- const fileStream = fs.createReadStream(filepath);
- const rl = readline.createInterface({
- input: fileStream,
- crlfDelay: Infinity
- });
- for await (const line of rl) {
- log.push(line);
- }
- for (const l of log.reverse()) {
- logs.push(l);
- if (logs.length >= requiredLogs) {
- break
- }
- }
- }
- } catch (e) {
- logger.info('读取文件发生异常咯~~~', e.message);
- }
- return logs;
- }
- async function getLatestLogEntries(dirPath, logFiles, requiredLogs = 100) {
- const MAX_LOGS = requiredLogs;
- let logs = [];
- try {
- for (const file of logFiles) {
-
- const filepath = `${dirPath}/${file}`;
- logger.info('文件~~~', filepath);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- const stats = fs.statSync(filepath);
- let position = stats.size;
- const chunkSize = 1 * 1024 * 1024;
-
- while (position > 0 && logs.length < MAX_LOGS) {
- const readSize = Math.min(chunkSize, position);
- const readStream = fs.createReadStream(filepath, {
- start: position - readSize,
- end: position - 1,
- highWaterMark: readSize
- });
-
- let buffer = '';
- await new Promise((resolve, reject) => {
- readStream.on('data', (chunk) => {
- buffer = chunk.toString() + buffer;
- });
- readStream.on('end', () => {
-
- const lines = buffer.split('\n');
- while (lines.length > 0) {
- const line = lines.pop();
- if (line) {
- logs.unshift(line);
-
- if (logs.length >= requiredLogs) break;
- }
- }
- resolve();
- });
- readStream.on('error', (err) => {
- console.error('读取文件发生错误:', err);
- reject(err);
- });
- readStream.on('close', () => {
- if (logs.length >= MAX_LOGS) {
- readStream.destroy();
- } else {
- logger.info('----继续读取~~', logs.length);
- }
- });
- });
- position -= readSize;
- }
-
- if (logs.length >= MAX_LOGS) {
- break;
- }
- }
- } catch (e) {
- logger.info('读取文件发生异常咯~~~', e.message);
- }
-
- return logs.reverse();
- }
- async function readLinesFromEnd(filePath, maxLines) {
- const lines = [];
- const fileSize = fs.statSync(filePath).size;
- const chunkSize = 1024 * 10 * 5;
- try {
- if (fileSize < chunkSize) {
- const fileStream = fs.createReadStream(filePath, {
- start: Math.max(0, 0),
- end: fileSize
- });
- let buffer = '';
- for await (const chunk of fileStream) {
- buffer = chunk + buffer;
- let lineEndIndex = buffer.length;
- while (lineEndIndex >= 0 && lines.length < maxLines) {
- const lineStartIndex = buffer.lastIndexOf('\n', lineEndIndex - 1);
- if (lineStartIndex === -1) {
- break;
- }
- const line = buffer.substring(lineStartIndex + 1, lineEndIndex).trim();
- if (line) {
- lines.push(line);
- }
- lineEndIndex = lineStartIndex;
- }
- if (lines.length >= maxLines) {
- break;
- }
- }
- } else {
- let forNum = (fileSize / chunkSize) + 1;
- for (let i = 1; i <= forNum; i++) {
- let position = fileSize - chunkSize * i;
- let z = position + chunkSize
- const fileStream = fs.createReadStream(filePath, {
- start: Math.max(position, 0),
- end: z
- });
- let buffer = '';
- for await (const chunk of fileStream) {
- buffer = chunk + buffer;
- let lineEndIndex = buffer.length;
- while (lineEndIndex >= 0 && lines.length < maxLines) {
- const lineStartIndex = buffer.lastIndexOf('\n', lineEndIndex - 1);
- if (lineStartIndex === -1) {
- break;
- }
- const line = buffer.substring(lineStartIndex + 1, lineEndIndex).trim();
- if (line) {
- lines.push(line);
- }
- lineEndIndex = lineStartIndex;
- }
- if (lines.length >= maxLines) {
- break;
- }
- position -= chunkSize;
- if (position < 0) {
- position = 0;
- }
- }
- }
- }
- } catch (e) {
- logger.info('读取文件发生异常咯~~~1', e.message);
- }
- return lines.reverse();
- }
- async function readLines(filePath, maxLines) {
- const fileStream = fs.createReadStream(filePath);
- const rl = readline.createInterface({
- input: fileStream,
- crlfDelay: Infinity
- });
- const lines = [];
- for await (const line of rl) {
- lines.push(line);
- if (lines.length >= maxLines) {
- break;
- }
- }
- rl.close();
- fileStream.close();
- return lines;
- }
- module.exports = {
- dowFile,
- checkFilePath,
- checkPathSync,
- writeFile,
- copyFileSync,
- readLastNLines,
- getLatestLogEntries,
- getRecentLogs,
- getLastFile
- }
|