A
A
arlovski2014-11-29 02:52:29
JavaScript
arlovski, 2014-11-29 02:52:29

How to write a handler in NodeJS that sends a request before the process terminates?

Hello.
There is an external module that logs messages to an array on the server and periodically sends them via http to another server. It is necessary to force the entire contents of the array to be sent before the process terminates. Something like:

var request = require('request');
var drainArray = function() {
  var options = {...};
  request(options, callback)
}
process.stdin.resume();
process.on('exit', drainArray);

is there any way to make sure that the request is sent (the response is not important) before the process is terminated, other than using a blocking event loop code - while() {}
I know this is an antipattern, but still

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrey Burov, 2014-11-29
@BuriK666

nodejs.org/api/process.html#process_event_exit
Will fail.

T
Timur Shemsedinov, 2014-11-29
@MarcusAurelius

Watching how the process ends, if by signals, then try:

//do something when app is closing
process.on('SIGINT', drainArray); // выход по Ctrl-C из консоли
process.on('SIGTERM', drainArray); // завершение через kill
process.on('exit', drainArray); // выход по собственному желанию
process.on('uncaughtException', drainArray); // если свалился

But make a global flag and check it in drainArray to avoid running 2 times:
var drainArray = function() {
  if (!process.flagExit) {
    process.flagExit = true;
    // отправка данных
  }
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question