index.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import os from 'os';
  2. import fs from 'fs';
  3. import path from 'path';
  4. // 一些常用的给工具函数
  5. // 1:------------ 获取本机器192xxxx地址
  6. export const getLocalIP = () => {
  7. const interfaces = os.networkInterfaces();
  8. for (let interfaceName in interfaces) {
  9. const interfaceList = interfaces[interfaceName];
  10. if (interfaceList) {
  11. for (let i = 0; i < interfaceList.length; i++) {
  12. const alias = interfaceList[i];
  13. if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
  14. return alias.address;
  15. }
  16. }
  17. }
  18. }
  19. return '0.0.0.0';
  20. };
  21. import svgCaptcha from 'svg-captcha';
  22. import dayjs from 'dayjs';
  23. // 2:------------ 生成验证码
  24. export const generateCaptcha = () => {
  25. const res = svgCaptcha.create({
  26. size: 4, // 验证码长度
  27. noise: 2, // 干扰线条数
  28. color: true, // 验证码字体颜色
  29. background: '#f0f0f0', // 背景颜色
  30. ignoreChars: '0oO1ilI', // 排除容易混淆的字符
  31. width: 120,
  32. height: 40,
  33. });
  34. return res;
  35. };
  36. //3:------------ 获取请求者ip 用来确定验证码是否正确
  37. export const ipLocResFu = (req: any) => {
  38. // 获取IP,并处理可能的IPv6格式
  39. let rawIp = req.socket.remoteAddress;
  40. // 简单的处理,如果包含`::ffff:`则去除,否则直接使用
  41. const clientIp = rawIp && rawIp.replace(/^.*:/, '');
  42. // console.log('客户端IP:', clientIp);
  43. return clientIp;
  44. };
  45. //4:------------ 追加内容写入文件
  46. export const AddTxtFileFu = (nowPath: any, fileName: string, content: string) => {
  47. const filePath = path.join(nowPath, fileName);
  48. // 在要追加的内容末尾加上换行符 `\n`
  49. const dataToAppend = dayjs().format('YYYY-MM-DD HH:mm:ss') + '------' + content + '\n';
  50. fs.appendFile(filePath, dataToAppend, 'utf8', (err) => {
  51. if (err) {
  52. return;
  53. }
  54. });
  55. };