Skip to content

Instantly share code, notes, and snippets.

@aleung
Created June 13, 2017 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleung/93254aa69eb4dc97d3ec2666d93047f8 to your computer and use it in GitHub Desktop.
Save aleung/93254aa69eb4dc97d3ec2666d93047f8 to your computer and use it in GitHub Desktop.
Test of [async-local-storage](https://github.com/vicanso/async-local-storage) on Node.js 8.x
Trace of ID 1
1497340609369: Received request. ID: 1
1497340609369: Step 1 1
1497340610599: Step 2 1
1497340610602: Response sent 1
-----
Trace of ID 2
1497340606575: Received request. ID: 2
1497340606575: Step 1 2
1497340612700: Step 2 2
1497340612700: Response sent 2
-----
const context = require('async-local-storage');
const http = require('http');
const util = require('util');
const url = require('url');
function trace(...args) {
let trace = context.get('trace');
if (!trace) {
trace = [];
context.set('trace', trace);
}
const t = Date.now();
trace.push(t + ': ' + args.join(' '));
}
function printTrace() {
const trace = context.get('trace');
const id = context.get('id');
console.log('Trace of ID ', id);
if (trace) {
trace.forEach( line => console.log(line) );
}
console.log('-----');
}
const delay = util.promisify(setTimeout);
async function step1() {
const id = context.get('id');
trace('Step 1', id);
await delay(Math.random() * 10000);
return step2();
}
function step2() {
const id = context.get('id');
trace('Step 2', id);
return 'Hello';
}
context.enable();
const server = http.createServer(async (req, res) => {
const reqId = url.parse(req.url, true).query.id;
trace('Received request. ID:', reqId);
context.set('id', reqId);
const content = await step1();
res.write(content);
res.end();
trace('Response sent', reqId);
printTrace();
});
server.listen(8080);
setInterval(() => {
console.log('Number of contexts:', context.size());
}, 1000);
{
"name": "tracing_test",
"version": "1.0.0",
"main": "index.js",
"author": "Leo Liang",
"license": "MIT",
"scripts": {
"start": "node index.js"
},
"dependencies": {
"async-local-storage": "^1.0.0"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment