0
process.on('unhandledRejection', (err, promise) => {
    console.log(`Error: ${err.message}`.red);
    //close server & exit process
    let server;
    server.close(() => process.exit(1));
});


C:\Users\Ford\Desktop\DevCamperAPI\server.js:48
    server.close(() => process.exit());
           ^

TypeError: Cannot read properties of undefined (reading 'close')

can someone help me with this?

I d like to know why i have this error, can someone help me with this ? nodejs

  • What server are you trying to close? when you declared it with `let server;`, you neither assigned a value to it nor a type (the last one would fix that specific error, but it probably wouldn't know what server to close). Pls share more details – João Casarin Nov 29 '22 at 02:45

2 Answers2

0

Your declaration let server is without assigning any value, server is undefined. So when you call close on undefined object you get this error.

Kudo
  • 328
  • 2
  • 8
0

The server variable is undefined in this case thus code execution fails when you try to call a method on an undefined variable. There are various ways to create a server using different node modules like https, http, hapi etc. If you have already defined server variable in your module outside this function then you can use that as well to close the server. One of the way to do it is:

var http = require('http');
var server = http.createServer(function (req, res) {
  res.write('Application starting');
  res.end();
});
server.listen(8080);

process.on('unhandledRejection', (err, promise) => {
    server.close(() => process.exit(1));
});
Saheed Hussain
  • 1,096
  • 11
  • 12