1// Flags: --expose-internals 2'use strict'; 3 4const common = require('../common'); 5const assert = require('assert'); 6const internal_async_hooks = require('internal/async_hooks'); 7const { spawn } = require('child_process'); 8const corruptedMsg = /async hook stack has become corrupted/; 9const heartbeatMsg = /heartbeat: still alive/; 10 11const { 12 newAsyncId, getDefaultTriggerAsyncId, 13 emitInit, emitBefore, emitAfter 14} = internal_async_hooks; 15 16const initHooks = require('./init-hooks'); 17 18if (process.argv[2] === 'child') { 19 const hooks = initHooks(); 20 hooks.enable(); 21 22 // Async hooks enforce proper order of 'before' and 'after' invocations 23 24 // Proper ordering 25 { 26 const asyncId = newAsyncId(); 27 const triggerId = getDefaultTriggerAsyncId(); 28 emitInit(asyncId, 'event1', triggerId, {}); 29 emitBefore(asyncId, triggerId); 30 emitAfter(asyncId); 31 } 32 33 // Improper ordering 34 // Emitting 'after' without 'before' which is illegal 35 { 36 const asyncId = newAsyncId(); 37 const triggerId = getDefaultTriggerAsyncId(); 38 emitInit(asyncId, 'event2', triggerId, {}); 39 40 console.log('heartbeat: still alive'); 41 emitAfter(asyncId); 42 } 43} else { 44 const args = ['--expose-internals'] 45 .concat(process.argv.slice(1)) 46 .concat('child'); 47 let errData = Buffer.from(''); 48 let outData = Buffer.from(''); 49 50 const child = spawn(process.execPath, args); 51 child.stderr.on('data', (d) => { errData = Buffer.concat([ errData, d ]); }); 52 child.stdout.on('data', (d) => { outData = Buffer.concat([ outData, d ]); }); 53 54 child.on('close', common.mustCall((code) => { 55 assert.strictEqual(code, 1); 56 assert.ok(heartbeatMsg.test(outData.toString()), 57 'did not crash until we reached offending line of code ' + 58 `(found ${outData})`); 59 assert.ok(corruptedMsg.test(errData.toString()), 60 'printed error contains corrupted message ' + 61 `(found ${errData})`); 62 })); 63} 64