Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active April 11, 2021 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rpivo/78ff32b50072d1dc851dda1dbade7f44 to your computer and use it in GitHub Desktop.
Save rpivo/78ff32b50072d1dc851dda1dbade7f44 to your computer and use it in GitHub Desktop.
Creating a Node Event Logger

Creating a Node Event Logger Class

Below is an example of a Node Event Logger class implementation that saves each event object that's emitted from an EventEmitter to a JSON array.

import fs from "fs";
import path from "path";

export default class EventLogger {
  constructor(emitter, logFileName) {
    this.emitter = emitter;
    this.filePath = path.join(process.cwd(), logFileName);
  }

  /* modified from:
   * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
   */
  replaceCircularReferences = () => {
    const seen = new WeakSet();

    return (_, value) => {
      if (typeof value === "object" && value !== null) {
        if (seen.has(value)) {
          return;
        }
        seen.add(value);
      }
      return value;
    };
  };

  fileExists = (file) => {
    try {
      if (fs.statSync(file)) return true;
    } catch {
      return false;
    }
  };

  getFileContents = (file) => {
    if (this.fileExists(file)) {
      try {
        return fs.readFileSync(file, "utf8");
      } catch (e) {
        console.log("error in function getFileContents", e);
      }
    } else {
      const contents = "[]";
      fs.writeFileSync(this.filePath, contents);
      return contents;
    }
  };

  logEvent = (eventName, event) => {
    const contents = JSON.parse(this.getFileContents(this.filePath));

    contents.push({ [eventName]: event });

    console.log(`${contents.length} events captured.`);

    fs.writeFileSync(
      this.filePath,
      JSON.stringify(contents, this.replaceCircularReferences()),
      { encoding: "utf8" }
    );
  };

  registerEvent = (eventName) => {
    this.emitter.on(eventName, (event) => this.logEvent(eventName, event));
  };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment