weikee94 / blog-api

Node.js 从零开发web server博客项目
0 stars 0 forks source link

07 博客项目日志 #4

Open weikee94 opened 4 years ago

weikee94 commented 4 years ago

日志

weikee94 commented 4 years ago

Stream

process.stdin.pipe(process.stdout);

const fileName1 = path.resolve(dirname, "data.txt"); const fileName2 = path.resolve(dirname, "data_to.txt");

const readStream = fs.createReadStream(fileName1); const writeStream = fs.createWriteStream(fileName2);

readStream.pipe(writeStream); readStream.on("data", (chunk) => { console.log(chunk.toString()); }); readStream.on("end", () => { console.log("copy done"); });


- http 请求读取文件通过stream 方式
```js
const http = require("http");
const fs = require("fs");
const path = require("path");
const fileName1 = path.resolve(__dirname, "data.txt");
const server = http.createServer((req, res) => {
  if (req.method === "GET") {
    const readStream = fs.createReadStream(fileName1);
    readStream.pipe(res);
  }
});
server.listen(8000);
weikee94 commented 4 years ago

日志

写日志

const fs = require("fs");
const path = require("path");

// write logs
function writeLog(writeStream, log) {
  writeStream.write(log + "\n");
}

// 生成 write stream
function createWriteStream(fileName) {
  const fullFileName = path.join(__dirname, "../", "../", "logs", fileName);
  const writeStream = fs.createWriteStream(fullFileName, {
    flags: "a",
  });
  return writeStream;
}

// 写访问日志
const accessWriteStream = createWriteStream("access.log");
function access(log) {
  writeLog(accessWriteStream, log);
}

module.exports = { access };

日志拆分 crontab click here view more

copy.sh

#!/bin/sh
cd /Users/username/Desktop/blog-api/blog-1/logs
cp access.log $(date +%Y-%m-%d).access.log
echo "" > access.log

如何定时任务

日志分析 by using readline

const fs = require("fs");
const path = require("path");
const readline = require("readline");

// 文件名
const fileName = path.join(__dirname, "../", "../", "logs", "access.log");
// 创建 read stream
const readStream = fs.createReadStream(fileName);

// 创建 readline 对象
const rl = readline.createInterface({
  input: readStream,
});

let chromeNum = 0;
let sum = 0;

// 逐行读取
rl.on("line", (lineData) => {
  if (!lineData) {
    return;
  }

  // 记录总行数
  sum++;

  const arr = lineData.split(" -- ");
  if (arr[2] && arr[2].indexOf("Chrome") > 0) {
    // 累加 chrome 的数量
    chromeNum++;
  }
});

// 监听读取完成
rl.on("close", () => {
  console.log("chrome: ", chromeNum / sum);
});