UNPKG

1.41 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const path = require("path");
4const timestamp = () => new Date().toISOString();
5let timer;
6const wait = (ms) => new Promise(resolve => {
7 if (timer)
8 timer.unref();
9 timer = setTimeout(() => resolve(), ms);
10});
11function chomp(s) {
12 if (s.endsWith('\n'))
13 return s.replace(/\n$/, '');
14 return s;
15}
16class Logger {
17 // eslint-disable-next-line no-useless-constructor
18 constructor(file) {
19 this.file = file;
20 this.flushing = Promise.resolve();
21 this.buffer = [];
22 }
23 log(msg) {
24 const stripAnsi = require('strip-ansi');
25 msg = stripAnsi(chomp(msg));
26 const lines = msg.split('\n').map(l => `${timestamp()} ${l}`.trimRight());
27 this.buffer.push(...lines);
28 // tslint:disable-next-line no-console
29 this.flush(50).catch(console.error);
30 }
31 async flush(waitForMs = 0) {
32 await wait(waitForMs);
33 this.flushing = this.flushing.then(async () => {
34 if (this.buffer.length === 0)
35 return;
36 const mylines = this.buffer;
37 this.buffer = [];
38 const fs = require('fs-extra');
39 await fs.mkdirp(path.dirname(this.file));
40 await fs.appendFile(this.file, mylines.join('\n') + '\n');
41 });
42 await this.flushing;
43 }
44}
45exports.Logger = Logger;