file.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. const fs = require('fs');
  2. const path = require('path');
  3. const {logger} = require("./logger");
  4. const {rustConfig} = require("../config");
  5. const http = require("./http");
  6. const readline = require('readline');
  7. // 检查目录是否存在,不存在新建
  8. function checkPathSync(filePath) {
  9. // 将相对路径转换为绝对路径
  10. const directoryPath = path.resolve(filePath);
  11. // 同步检查目录是否存在
  12. if (!fs.existsSync(directoryPath)) {
  13. // 目录不存在,需要创建它
  14. logger.info('目录不存在,正在创建...');
  15. try {
  16. // 同步创建目录
  17. fs.mkdirSync(directoryPath, {recursive: true});
  18. logger.info('目录已成功创建');
  19. } catch (error) {
  20. // 创建目录失败
  21. logger.error('创建目录失败:', error);
  22. return false
  23. }
  24. } else {
  25. // 目录已存在
  26. logger.info('目录已存在');
  27. }
  28. return true
  29. }
  30. // 检查文件是否存在
  31. function checkFilePath(filePath) {
  32. // 同步检查文件是否存在
  33. const directoryPath = path.resolve(filePath);
  34. if (fs.existsSync(directoryPath)) {
  35. logger.info('文件存在:' + filePath);
  36. return true
  37. } else {
  38. logger.error('文件不存在:' + filePath);
  39. return false
  40. }
  41. }
  42. // 创建文件
  43. function writeFile(filePath, text, breakFun) {
  44. fs.writeFile(filePath, text, (err) => {
  45. if (err) {
  46. logger.error('写入文件时发生错误:', err);
  47. breakFun(err)
  48. } else {
  49. logger.log('文件已成功写入!');
  50. breakFun(null, true)
  51. }
  52. });
  53. }
  54. // 同步复制
  55. function copyFileSync(source, destination) {
  56. try {
  57. // 同步复制文件
  58. fs.copyFileSync(source, destination);
  59. // logger.info("成功");
  60. return true;
  61. } catch (err) {
  62. return false;
  63. // logger.info("失败");
  64. }
  65. }
  66. // // 读取日志(倒叙)指定行数
  67. // function readLastNLines(filePath, n) {
  68. // const content = fs.readFileSync(filePath, 'utf8');
  69. // const lines = content.trim().split('\n');
  70. // const lastNLines = lines.slice(-n).join('\n');
  71. //
  72. // // 此处处理或输出最后n行的内容
  73. // // console.log(lastNLines);
  74. // return lastNLines.split("\n").reverse();
  75. // }
  76. // 下载文件
  77. function dowFile(url, fileName, dowPath, headers) {
  78. return http.dowFile(url, fileName, dowPath, headers)
  79. }
  80. // 删除文件
  81. function delFile() {
  82. }
  83. /***********************************/
  84. function getLastFile(dirPath, number, callback) {
  85. fs.readdir(dirPath, async (err, files) => {
  86. if (err) {
  87. logger.error(`无法列出目录。`, err);
  88. // process.exit(1);
  89. } else {
  90. let fileList = [];
  91. //提示日志默认是根据日志生成的,拿到的files 也是 按照生成日志排序的,所以
  92. // 按照倒叙获取,如果一个文件内容满足num,就不在继续查询,如果不够,继续获取文件
  93. // logger.info("文件:",files)
  94. for (file of files) {
  95. const filePath = path.join(dirPath, file);
  96. const stats = await fs.promises.stat(filePath);
  97. if (stats.isFile()) {
  98. fileList.push({name: file, time: stats.birthtime.getTime()});
  99. // logger.info("文件:" + filePath + "时间:" + stats.birthtime.getTime())
  100. }
  101. }
  102. fileList.sort((a, b) => b.time - a.time);
  103. // for (a of fileList) {
  104. // logger.info("文件cccccccc22222222:" + a.name + "\ttime:" + a.time)
  105. // }
  106. lastFileList = fileList.slice(0, number != -1 ? number : fileList.length);
  107. lastFileNameList = lastFileList.map((item) => item.name);
  108. callback(lastFileNameList.reverse(), lastFileList.reverse());
  109. }
  110. });
  111. }
  112. // 读取日志(倒叙)指定行数
  113. async function readLastNLines(dirPath, filePathList, n) {
  114. try {
  115. // for (var i = 0; i < filePathList.length; i++) {
  116. // var item = filePathList[i];
  117. // logger.info("日志文件2222222:" + item)
  118. // }
  119. const fileList = [];
  120. var count = 0;
  121. for (var i = filePathList.length - 1; i >= 0; i--) {
  122. var item = filePathList[i];
  123. const filepath = `${dirPath}/${item}`;
  124. logger.info("日志文件:" + filepath)
  125. //老版本 加载整个文件
  126. // const content = fs.readFileSync(`${filepath}`, "utf8");
  127. // let lines = content.trim().split("\n");
  128. //新版本:流式读取和逐行处理
  129. const lines = await readLinesFromEnd(filepath, n - count);
  130. // logger.info("日:" + lines)
  131. fileList.push({
  132. filePath: item,
  133. lines: lines,
  134. })
  135. count += lines.length;
  136. if (count >= n) {
  137. break
  138. }
  139. }
  140. fileList.reverse();
  141. // const allFile = [].concat(...fileList.map((item) => item.lines));
  142. // let lastNLines = allFile.slice(-n).join("\n");
  143. // return lastNLines.split("\n").reverse();
  144. const allFile = [].concat(...fileList.map((item) => item.lines));
  145. const lastNLines = allFile.slice(-n).reverse();
  146. return lastNLines;
  147. } catch (e) {
  148. logger.info('获取日志异常了~~1111111111111111', e);
  149. }
  150. }
  151. async function readLinesFromEnd(filePath, maxLines) {
  152. const lines = [];
  153. const fileSize = fs.statSync(filePath).size;
  154. const chunkSize = 1024 * 10 * 5; // 每次读取的块大小
  155. if (fileSize < chunkSize) {
  156. const fileStream = fs.createReadStream(filePath, {
  157. start: Math.max(0, 0),
  158. end: fileSize
  159. });
  160. let buffer = '';
  161. for await (const chunk of fileStream) {
  162. buffer = chunk + buffer;
  163. let lineEndIndex = buffer.length;
  164. while (lineEndIndex >= 0 && lines.length < maxLines) {
  165. const lineStartIndex = buffer.lastIndexOf('\n', lineEndIndex - 1);
  166. if (lineStartIndex === -1) {
  167. break;
  168. }
  169. const line = buffer.substring(lineStartIndex + 1, lineEndIndex).trim();
  170. if (line) {
  171. lines.push(line);
  172. }
  173. lineEndIndex = lineStartIndex;
  174. }
  175. if (lines.length >= maxLines) {
  176. break;
  177. }
  178. }
  179. } else {
  180. let forNum = (fileSize / chunkSize) + 1;
  181. for (let i = 1; i <= forNum; i++) {
  182. let position = fileSize - chunkSize * i;
  183. let z = position + chunkSize
  184. const fileStream = fs.createReadStream(filePath, {
  185. start: Math.max(position, 0),
  186. end: z
  187. });
  188. let buffer = '';
  189. for await (const chunk of fileStream) {
  190. buffer = chunk + buffer;
  191. let lineEndIndex = buffer.length;
  192. while (lineEndIndex >= 0 && lines.length < maxLines) {
  193. const lineStartIndex = buffer.lastIndexOf('\n', lineEndIndex - 1);
  194. if (lineStartIndex === -1) {
  195. break;
  196. }
  197. const line = buffer.substring(lineStartIndex + 1, lineEndIndex).trim();
  198. if (line) {
  199. lines.push(line);
  200. }
  201. lineEndIndex = lineStartIndex;
  202. }
  203. if (lines.length >= maxLines) {
  204. break;
  205. }
  206. position -= chunkSize;
  207. if (position < 0) {
  208. position = 0;
  209. }
  210. }
  211. }
  212. }
  213. return lines;
  214. }
  215. async function readLines(filePath, maxLines) {
  216. const fileStream = fs.createReadStream(filePath);
  217. const rl = readline.createInterface({
  218. input: fileStream,
  219. crlfDelay: Infinity
  220. });
  221. const lines = [];
  222. for await (const line of rl) {
  223. lines.push(line);
  224. if (lines.length >= maxLines) {
  225. break;
  226. }
  227. }
  228. rl.close();
  229. fileStream.close();
  230. return lines;
  231. }
  232. module.exports = {
  233. dowFile,
  234. checkFilePath,
  235. checkPathSync,
  236. writeFile,
  237. copyFileSync,
  238. readLastNLines,
  239. getLastFile
  240. }