Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Section 1
- var express = require('express');
- const bodyParser = require('body-parser');
- const { EventEmitter } = require('events');
- const morgan = require('morgan');
- const app = express();
- const profilingEventEmitter = new EventEmitter();
- // Section 2
- profilingEventEmitter.on('middleware', ({ req, name, elapsedMS }) => {
- console.log(req.method, req.url, ':', name, `${elapsedMS}ms`);
- });
- // Section 3
- var profiler = function(fn) {
- if (fn.length === 2) {
- return function (req, res) {
- const start = Date.now();
- res.once('finish', () => profilingEventEmitter.emit('middleware', {
- req,
- name: fn.name,
- elapsedMS: Date.now() - start
- }));
- return fn.apply(this, arguments);
- };
- } else if (fn.length === 3) {
- return function (req, res, next) {
- const start = Date.now();
- fn.call(this, req, res, function () {
- profilingEventEmitter.emit('middleware', {
- req,
- name: fn.name,
- elapsedMS: Date.now() - start
- });
- next.apply(this, arguments);
- });
- };
- } else {
- throw new Error('Function must take 2 or 3 arguments');
- }
- }
- // Section 4
- app.use(profiler(morgan('dev')));
- app.use(profiler(bodyParser.json()));
- app.use(profiler(express.static('public')));
- // Section 5
- app.get('/check', profiler(function userRequestHandling(req, res) {
- setTimeout(() => res.send('Done'), 2);
- }));
- app.listen(3000);
Add Comment
Please, Sign In to add comment