Add intentional latency in express

2020-02-26 02:57发布

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/

Im calling the http://localhost:3000/wines via ajax (the content doesn't matter). But I want to test latency. Can I do something like make express respond after 2 seconds? (I want to simulate the ajax loader and I'm running on localhost so my latency is pretty much nil)

7条回答
Juvenile、少年°
2楼-- · 2020-02-26 03:21
app.get('/fakeDelay', function(req,res){
    let ms = req.query.t;
    ms = (ms>5000 || isNaN(ms)) ? 1000 : parseInt(ms); 
    setTimeout((()=> res.status(200).send({delay:ms})), ms);
})

Then request the URL as: http://localhost/fakeDelay/?t=2000

(max 5000ms and default of 1000ms on this example)

查看更多
▲ chillily
3楼-- · 2020-02-26 03:27

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

查看更多
闹够了就滚
4楼-- · 2020-02-26 03:30

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

查看更多
老娘就宠你
5楼-- · 2020-02-26 03:32

Use as middleware, for all your requests

  app.use(function(req,res,next){setTimeout(next,1000)});
查看更多
beautiful°
6楼-- · 2020-02-26 03:32

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)});

查看更多
等我变得足够好
7楼-- · 2020-02-26 03:33

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)
        });

});
查看更多
登录 后发表回答