Skip to content

Instantly share code, notes, and snippets.

@shigeya-dd
Last active July 19, 2020 14:17
Show Gist options
  • Save shigeya-dd/7daa92f724153ac32dc4a2799e5790ad to your computer and use it in GitHub Desktop.
Save shigeya-dd/7daa92f724153ac32dc4a2799e5790ad to your computer and use it in GitHub Desktop.
Slowing nginx randomly with njs

Slowing nginx randomly with njs

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.

wait.js

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.

nginx.conf

...
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 scripting language

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.

--> https://nginx.org/en/linux_packages.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment