1'use strict'; 2 3const common = require('../common'); 4const sleep = require('util').promisify(setTimeout); 5const assert = require('assert'); 6const { executionAsyncResource, createHook } = require('async_hooks'); 7const { createServer, get } = require('http'); 8const sym = Symbol('cls'); 9 10// Tests continuation local storage with the currentResource API 11// through an async function 12 13assert.ok(executionAsyncResource()); 14 15createHook({ 16 init(asyncId, type, triggerAsyncId, resource) { 17 const cr = executionAsyncResource(); 18 resource[sym] = cr[sym]; 19 } 20}).enable(); 21 22async function handler(req, res) { 23 executionAsyncResource()[sym] = { state: req.url }; 24 await sleep(10); 25 const { state } = executionAsyncResource()[sym]; 26 res.setHeader('content-type', 'application/json'); 27 res.end(JSON.stringify({ state })); 28} 29 30const server = createServer(function(req, res) { 31 handler(req, res); 32}); 33 34function test(n) { 35 get(`http://localhost:${server.address().port}/${n}`, common.mustCall(function(res) { 36 res.setEncoding('utf8'); 37 38 let body = ''; 39 res.on('data', function(chunk) { 40 body += chunk; 41 }); 42 43 res.on('end', common.mustCall(function() { 44 assert.deepStrictEqual(JSON.parse(body), { state: `/${n}` }); 45 })); 46 })); 47} 48 49server.listen(0, common.mustCall(function() { 50 server.unref(); 51 for (let i = 0; i < 10; i++) { 52 test(i); 53 } 54})); 55