JeremyJaydan
5/31/2018 - 11:40 AM

NodeJS-console.log-Timeline-function.js

function Timeline(timelineLabel){
	this.times = [];
	this.maxChars = 0;
	this.label = timelineLabel;
	this.add = function(label){
		let times = this.times;
		times.push({ label, hrtime: process.hrtime(), elapsed: times.length === 0 ? [0, 0] : process.hrtime(times[times.length - 1].hrtime) });
		if(this.maxChars < label.length) this.maxChars = label.length;
		return this;
	};
	this.log = function(){
		console.log("\n\n  [ "+ this.label +" ]\n\n" + this.times.map(time => "  " + time.label + (" ".repeat((this.maxChars - time.label.length) + 2)) + (time.elapsed[1] / 1000000) + "ms").join("\n"), "\n");
		return this;
	};
}

Simple node.js interim logging function

(uses process.hrtime)

// Create the timeline
const timeline = new Timeline("timeline label here");

// add to the timeline
timeline.add("time label here");

// log the timeline
timeline.log();

The returned time is determined by the previous timeline item. For example if the time between item 1 & item 2 was 100ms, item 2 will be 100ms.

Example: