utils.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import fs from 'fs';
  2. import { networkInterfaces } from 'os';
  3. import dotenv from 'dotenv';
  4. export const isFunction = (arg: unknown): arg is (...args: any[]) => any =>
  5. typeof arg === 'function';
  6. export const isRegExp = (arg: unknown): arg is RegExp =>
  7. Object.prototype.toString.call(arg) === '[object RegExp]';
  8. /*
  9. * Read all files in the specified folder, filter through regular rules, and return file path array
  10. * @param root Specify the folder path
  11. * [@param] reg Regular expression for filtering files, optional parameters
  12. * Note: It can also be deformed to check whether the file path conforms to regular rules. The path can be a folder or a file. The path that does not exist is also fault-tolerant.
  13. */
  14. export function readAllFile(root: string, reg: RegExp) {
  15. let resultArr: string[] = [];
  16. try {
  17. if (fs.existsSync(root)) {
  18. const stat = fs.lstatSync(root);
  19. if (stat.isDirectory()) {
  20. // dir
  21. const files = fs.readdirSync(root);
  22. files.forEach(function (file) {
  23. const t = readAllFile(root + '/' + file, reg);
  24. resultArr = resultArr.concat(t);
  25. });
  26. } else {
  27. if (reg !== undefined) {
  28. if (isFunction(reg.test) && reg.test(root)) {
  29. resultArr.push(root);
  30. }
  31. } else {
  32. resultArr.push(root);
  33. }
  34. }
  35. }
  36. } catch (error) {}
  37. return resultArr;
  38. }
  39. export function getIPAddress() {
  40. let interfaces = networkInterfaces();
  41. for (let devName in interfaces) {
  42. let iFace = interfaces[devName];
  43. if (!iFace) return;
  44. for (let i = 0; i < iFace.length; i++) {
  45. let alias = iFace[i];
  46. if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
  47. return alias.address;
  48. }
  49. }
  50. }
  51. return '';
  52. }
  53. export function isDevFn(): boolean {
  54. return process.env.NODE_ENV === 'development';
  55. }
  56. export function isProdFn(): boolean {
  57. return process.env.NODE_ENV === 'production';
  58. }
  59. export function isReportMode(): boolean {
  60. return process.env.REPORT === 'true';
  61. }
  62. export function loadEnv() {
  63. const env = process.env.NODE_ENV;
  64. const ret: any = {};
  65. const envList = [`.env.${env}.local`, `.env.${env}`, '.env.local', '.env', ,];
  66. envList.forEach((e) => {
  67. dotenv.config({
  68. path: e,
  69. });
  70. });
  71. for (const envName of Object.keys(process.env)) {
  72. const realName = (process.env as any)[envName].replace(/\\n/g, '\n');
  73. ret[envName] = realName;
  74. process.env[envName] = realName;
  75. }
  76. return ret;
  77. }