I needed to add some random latency to my nginx server to simulate slower network. So, I created small njs (nginx javascript) snipet to implement the latency.
var fs = require('fs');
var INDEX = "/usr/share/nginx/html/index.html";
function hello(r){
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
try { var data = fs.readFileSync(INDEX); } catch (e) {}
r.headersOut['Content-Type'] = "text/html";
sleep(Math.floor(Math.random()*1000)).then(() => { r.return(200, data); });
}
export default {hello};
- Adding latency to the top page only to make things simple.
- To add latency to the whole contents, I'm considering to host contents on another port and call them by subrequests. (Not tried yet)
- This code adds random latency less than 1000msec before response.
...
load_module modules/ngx_http_js_module.so; # Load njs module
...
http {
...
js_import wait.js; # Import javascript code.
# Assuming it's in the same directory with nginx.conf
...
server {
location = / { # Apply to the top page only
js_content wait.hello; # Execute wait.hello to respond
}
location / { # Other contents
}
...
njs is a subset of the JavaScript language that allows extending nginx functionality.
--> http://nginx.org/en/docs/njs/
njs module may not be provided by the linux distributions. In those cases, try nginx.org repository.