1

my nodejs module starts a server on a specific port, I am wondering if it is a way to stop the execution of that server in my mocha test:

Let's assume that myserver.js contains something like:

myserver = http.Server(app);
....
process.on('SIGTERM', ()=>{ ... });

and in my mocha test, If I do something like this: in order to load my class:

   it(' starts the execution and then stop the server() {
     require('../myserver.js');

     ????
    }

How can I stop the execution from test case?
I was wondering if I could send a SIGTERM message to that process, but I should discover the pid of that process first, maybe it is not worth to do that.

I assume that I could export from my module a function that is then used from other modules in some specific circumstances, like the one I want to test, in order to stop the overall execution.

user1971444
  • 57
  • 1
  • 9

1 Answers1

0

In case you need to send the command a SIGTERM signal, you need to handle that with the process signal handler:

Note: process does not require a “require”, it’s automatically available.

const express = require('express')

const app = express()

app.get('/', (req, res) => {
  res.send('Hi!')
});

const server = app.listen(3000, () => console.log('Server ready'));

process.on('SIGTERM', () => {
  server.close(() => {
    console.log('Process terminated');
  });
});

What are signals? Signals are a POSIX intercommunication system: a notification sent to a process in order to notify it of an event that occurred.

SIGKILL is the signals that tells a process to immediately terminate, and would ideally act like process.exit().

SIGTERM is the signals that tells a process to gracefully terminate. It is the signal that’s sent from process managers like upstart or supervisord and many others.

You can send this signal from inside the program, in another function:

process.kill(process.pid, 'SIGTERM')

Or from another Node.js running program, or any other app running in your system that knows the PID of the process you want to terminate.

  • 1
    I agree with you, but the problem is to understand how to recover the pid of the server class, in order to send a sigterm to another loaded module, in this case the server class from my mocha test suite. I think that this is the approach if I don't export any function that helps me to close the server – user1971444 Feb 08 '22 at 13:14