Skip to content

Commit 56492f7

Browse files
committed
Node Issue #309, update to eliminate confusion of certain flush processes
1 parent e390de5 commit 56492f7

File tree

1 file changed

+79
-0
lines changed
  • src/connections/sources/catalog/libraries/server/node

1 file changed

+79
-0
lines changed

src/connections/sources/catalog/libraries/server/node/index.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,85 @@ analytics.flush(function(err, batch){
437437
});
438438
```
439439

440+
## Long running process
441+
442+
You should call client.track(...) and know that events will be queued and eventually sent to Segment, also to prevent losing messages make sure that you capture any interruption (for example, a server restart) and call flush to know of and delay the process shutdown.
443+
444+
```js
445+
import { randomUUID } from 'crypto';
446+
import Analytics from 'analytics-node'
447+
448+
const WRITE_KEY = '...';
449+
450+
const analytics = new Analytics(WRITE_KEY, { flushAt: 10 });
451+
452+
analytics.track({
453+
anonymousId: randomUUID(),
454+
event: 'Test event',
455+
properties: {
456+
name: 'Test event',
457+
timestamp: new Date()
458+
}
459+
});
460+
461+
const exitGracefully = async (code) => {
462+
console.log('Flushing events');
463+
await analytics.flush(function(err, batch) {
464+
console.log('Flushed, and now this program can exit!');
465+
process.exit(code);
466+
});
467+
};
468+
469+
[
470+
'beforeExit', 'uncaughtException', 'unhandledRejection',
471+
'SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP',
472+
'SIGABRT','SIGBUS', 'SIGFPE', 'SIGUSR1', 'SIGSEGV',
473+
'SIGUSR2', 'SIGTERM',
474+
].forEach(evt => process.on(evt, exitGracefully));
475+
476+
function logEvery2Seconds(i) {
477+
setTimeout(() => {
478+
console.log('Infinite Loop Test n:', i);
479+
logEvery2Seconds(++i);
480+
}, 2000);
481+
}
482+
483+
logEvery2Seconds(0);
484+
```
485+
486+
# Short lived process
487+
488+
Short-lived functions have a predictably short and linear lifecycle so use a queue big enough to hold all messages and then
489+
await for flush to complete it's work.
490+
491+
492+
```js
493+
import { randomUUID } from 'crypto';
494+
import Analytics from 'analytics-node'
495+
496+
497+
async function lambda()
498+
{
499+
const WRITE_KEY = '...';
500+
const analytics = new Analytics(WRITE_KEY, { flushAt: 20 });
501+
analytics.flushed = true;
502+
503+
analytics.track({
504+
anonymousId: randomUUID(),
505+
event: 'Test event',
506+
properties: {
507+
name: 'Test event',
508+
timestamp: new Date()
509+
}
510+
});
511+
await analytics.flush(function(err, batch) {
512+
console.log('Flushed, and now this program can exit!');
513+
});
514+
}
515+
516+
lambda();
517+
```
518+
440519

441520
## Multiple Clients
442521

0 commit comments

Comments
 (0)