Skip to content

Instantly share code, notes, and snippets.

@sidwebworks
Created August 21, 2022 23:18
Show Gist options
  • Save sidwebworks/8dda0071a307a2c48e0531fa48b63243 to your computer and use it in GitHub Desktop.
Save sidwebworks/8dda0071a307a2c48e0531fa48b63243 to your computer and use it in GitHub Desktop.
Node async test
'use strict';
const fs = require('fs');
const crypto = require('crypto');
const http = require('http');
// Current timestamp
const start = Date.now();
// Simple Logging util
const log = (name, ...args) => {
const diff = Date.now() - start;
const msg = `[${name.toUpperCase()}]: TIME: ${diff}ms`;
process.stdout.write([msg, ...args, '\n\n'].join(' '));
};
function work() {
process.nextTick(() => log('process.nextTick', 'Draining nextTicks queue'));
setImmediate(() =>
log('setImmediate', 'reached the end of the current loop iteration')
);
setTimeout(() => log('Timers'), 1000);
queueMicrotask(() => log('Micro task'));
// Some file IO
fs.readFile(__filename, () => {
log('File IO');
});
// Expensive hash
crypto.pbkdf2('password', 'saltyyy', 10000, 512, 'sha512', () => {
log(`pbkdf2`);
});
let count = 1000000000;
// Some blocking code
while (count) {
count--;
}
log('Blocking', `count is ${count}`);
}
const server = http.createServer((req, res) => {
log('REQ INCOMING', req.url);
if (req.url?.includes('kill')) {
server.close();
}
req.on('readable', () => {
log('REQ READABLE');
work();
});
req.on('end', () => {
res.end();
});
req.on('close', () => {
log(`REQ CLOSE`);
});
});
process.on('exit', () => {
log('EXIT', 'Event loop is down. Gotta go now...');
});
server.on('close', () => {
log(`Server CLOSE`);
});
server.on('listening', () => {
log(`Server listening`);
});
work(); // Initial run
server.listen(3000);
/**
STDOUT:
[BLOCKING]: TIME: 478ms count is 0
[PROCESS.NEXTTICK]: TIME: 481ms Draining nextTicks queue
[SERVER LISTENING]: TIME: 481ms
[MICRO TASK]: TIME: 481ms
[PBKDF2]: TIME: 481ms
[SETIMMEDIATE]: TIME: 482ms reached the end of the current loop iteration
[FILE IO]: TIME: 482ms
[TIMERS]: TIME: 1002ms
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment