Add intentional latency in express

后端 未结 7 2034
暖寄归人
暖寄归人 2020-12-29 18:37

Im using express with node.js, and testing certain routes. I\'m doing this tute at http://coenraets.org/blog/2012/10/creating-a-rest-api-using-node-js-express-and-mongodb/

相关标签:
7条回答
  • 2020-12-29 19:07

    Try connect-pause module. It adds delay to all or only some routes in your app.

    0 讨论(0)
  • 2020-12-29 19:10

    You could also just write your own generic delay handler using a Promise or callback (using a q promise in this case):

    pause.js:

    var q = require('q');
    
    function pause(time) {
        var deferred = q.defer();
    
        // if the supplied time value is not a number, 
        // set it to 0, 
        // else use supplied value
        time = isNaN(time) ? 0 : time;
    
        // Logging that this function has been called, 
        // just in case you forgot about a pause() you added somewhere, 
        // and you think your code is just running super-slow :)
        console.log('pause()-ing for ' + time + ' milliseconds');
    
        setTimeout(function () {
            deferred.resolve();
        }, time);
    
        return deferred.promise;
    }
    
    module.exports = pause;
    

    then use it however you'd like:

    server.js:

    var pause = require('./pause');
    
    router.get('/items', function (req, res) {
        var items = [];
    
        pause(2000)
            .then(function () {
                res.send(items)
            });
    
    });
    
    0 讨论(0)
  • 2020-12-29 19:14

    Just call res.send inside of a setTimeout:

    setTimeout((function() {res.send(items)}), 2000);
    
    0 讨论(0)
  • 2020-12-29 19:14

    To apply it globaly on all requests you can use the following code:

    app.use( ( req, res, next ) => {
        setTimeout(next, Math.floor( ( Math.random() * 2000 ) + 100 ) );
    });
    

    Time values are:

    Max = 2000 (sort of.... min value is added so in reality its 2100)

    Min = 100

    0 讨论(0)
  • 2020-12-29 19:18

    just add a comment on top of the solution of @maggocnx : put this middleware early (before your route handler)

    app.use(function(req,res,next){setTimeout(next,1000)});

    0 讨论(0)
  • 2020-12-29 19:25

    Use as middleware, for all your requests

      app.use(function(req,res,next){setTimeout(next,1000)});
    
    0 讨论(0)
提交回复
热议问题