|
| 1 | +const EventEmitter = require("events"); |
| 2 | +const fs = require("fs"); |
| 3 | +const promisify = require("./promisify"); |
| 4 | + |
| 5 | +class WithTime extends EventEmitter { |
| 6 | + async execute(asyncFunc, ...args) { |
| 7 | + this.emit("begin"); |
| 8 | + try { |
| 9 | + console.time("execute"); |
| 10 | + const data = await asyncFunc(...args); |
| 11 | + this.emit("data", data); |
| 12 | + console.timeEnd("execute"); |
| 13 | + this.emit("end"); |
| 14 | + } catch (err) { |
| 15 | + this.emit("error", err); |
| 16 | + } |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +const readFileAsArray = async file => { |
| 21 | + try { |
| 22 | + const readFile = promisify(fs.readFile); |
| 23 | + const data = await readFile([file]); |
| 24 | + const lines = data |
| 25 | + .toString() |
| 26 | + .trim() |
| 27 | + .split("\n"); |
| 28 | + return lines; |
| 29 | + } catch (error) { |
| 30 | + throw new Error(error); |
| 31 | + } |
| 32 | +}; |
| 33 | + |
| 34 | +const withTime = new WithTime(); |
| 35 | + |
| 36 | +withTime.on("begin", () => console.log("About to execute")); |
| 37 | +withTime.on("end", () => console.log("Done with execute")); |
| 38 | +withTime.on("data", data => { |
| 39 | + console.log(data); |
| 40 | +}); |
| 41 | +withTime.on("error", error => { |
| 42 | + console.log(error); |
| 43 | +}); |
| 44 | + |
| 45 | +const filename = "test.txt"; |
| 46 | +withTime.execute(readFileAsArray, filename); |
0 commit comments