实现简单的前端日志记录

359 阅读1分钟

注:基于node fs模块,读写文件

  • 项目环境为electron,自带node所以可以使用fs模块
  • 一天产生一个日志文件
  • 写入方法入参接收字符串
  • 日志文件路径可自设但需手动创建文件夹

封装工具函数 logRecord.ts

import fs from 'fs'
import { parseTime } from '@/utils/formateTime'
const path = `C:\\Users\\${parseTime(new Date()).substring(0, 10)}-logRecord.txt`

// 读取
export function openRead (): void {
  fs.readFile(path, 'utf8', function (err, datastr) {
    console.log('读取成功后的内容=======>' + err)
    console.log('读取成功后的内容=======>' + datastr)
  })
}

// 写入
export function openWrite (str: string): void {
  let newStr = ''
  // 设置文件名
  fs.access(path, (err) => {
    if (err) {
      // 文件不存在
      // path = `C:\\Users\\${parseTime(new Date())?.substring(0, 10)}-logRecord.txt`
      newStr = '日志记录' + parseTime(new Date()) + '\n' + parseTime(new Date()) + ' ' + str + '\n'
      fs.writeFile(path, newStr, function (err) {
        if (err) {
          return console.log(err + '首次写入失败')
        }
        console.log('首次写入成功')
      })
    } else {
      // 文件存在
      fs.readFile(path, 'utf8', function (_err, datastr) {
        // 成功读取
        newStr = datastr + parseTime(new Date()) + ' ' + str + '\n'
        fs.writeFile(path, newStr, function (err) {
          if (err) {
            return console.log(err + '非首次写入失败')
          }
          console.log('非首次写入成功')
        })
      })
    }
  })
}

使用页直接引入使用

import { openWrite } from '@....'

调用 openWrite(存储内容)