Emitted error event on server instance at

Ответили на вопрос 2 человека. Оцените лучшие ответы! И подпишитесь на вопрос, чтобы узнавать о появлении новых ответов.

Создал приложение — create-react-app app. Запустил — npm start.
Ошибка:

events.js:291
          throw er; // Unhandled 'error' event
          ^
    
    Error: spawn cmd ENOENT
        at Process.ChildProcess._handle.onexit (internal/child_process.js:268:19)
        at onErrorNT (internal/child_process.js:468:16)
        at processTicksAndRejections (internal/process/task_queues.js:80:21)     
    Emitted 'error' event on ChildProcess instance at:
        at Process.ChildProcess._handle.onexit (internal/child_process.js:274:12)
        at onErrorNT (internal/child_process.js:468:16)
        at processTicksAndRejections (internal/process/task_queues.js:80:21) {
      errno: -4058,
      code: 'ENOENT',
      syscall: 'spawn cmd',
      path: 'cmd',
      spawnargs: [ '/s', '/c', 'start', '""', '/b', '"http://localhost:3000/"' ]
    }
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! todo-list@0.1.0 start: `react-scripts start`
    npm ERR! Exit status 1
    npm ERR!
    npm ERR! Failed at the todo-list@0.1.0 start script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     C:UsersАлексAppDataRoamingnpm-cache_logs2020-08-13T12_14_12_199Z-debug.log

You will encounter various kinds of errors while developing Node.js
applications, but most can be avoided or easily mitigated with the right coding
practices. However, most of the information to fix these problems are currently
scattered across various GitHub issues and forum posts which could lead to
spending more time than necessary when seeking solutions.

Therefore, we’ve compiled this list of 15 common Node.js errors along with one
or more strategies to follow to fix each one. While this is not a comprehensive
list of all the errors you can encounter when developing Node.js applications,
it should help you understand why some of these common errors occur and feasible
solutions to avoid future recurrence.

🔭 Want to centralize and monitor your Node.js error logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

1. ECONNRESET

ECONNRESET is a common exception that occurs when the TCP connection to
another server is closed abruptly, usually before a response is received. It can
be emitted when you attempt a request through a TCP connection that has already
been closed or when the connection is closed before a response is received
(perhaps in case of a timeout). This exception will usually
look like the following depending on your version of Node.js:

Output

Error: socket hang up
    at connResetException (node:internal/errors:691:14)
    at Socket.socketOnEnd (node:_http_client:466:23)
    at Socket.emit (node:events:532:35)
    at endReadableNT (node:internal/streams/readable:1346:12)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'ECONNRESET'
}

If this exception occurs when making a request to another server, you should
catch it and decide how to handle it. For example, you can retry the request
immediately, or queue it for later. You can also investigate your timeout
settings if you’d like to wait longer for the request to be
completed.

On the other hand, if it is caused by a client deliberately closing an
unfulfilled request to your server, then you don’t need to do anything except
end the connection (res.end()), and stop any operations performed in
generating a response. You can detect if a client socket was destroyed through
the following:

app.get("/", (req, res) => {
  // listen for the 'close' event on the request
  req.on("close", () => {
    console.log("closed connection");
  });

  console.log(res.socket.destroyed); // true if socket is closed
});

2. ENOTFOUND

The ENOTFOUND exception occurs in Node.js when a connection cannot be
established to some host due to a DNS error. This usually occurs due to an
incorrect host value, or when localhost is not mapped correctly to
127.0.0.1. It can also occur when a domain goes down or no longer exists.
Here’s an example of how the error often appears in the Node.js console:

Output

Error: getaddrinfo ENOTFOUND http://localhost
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'http://localhost'
}

If you get this error in your Node.js application or while running a script, you
can try the following strategies to fix it:

Check the domain name

First, ensure that you didn’t make a typo while entering the domain name. You
can also use a tool like DNS Checker to confirm that
the domain is resolving successfully in your location or region.

Check the host value

If you’re using http.request() or https.request() methods from the standard
library, ensure that the host value in the options object contains only the
domain name or IP address of the server. It shouldn’t contain the protocol,
port, or request path (use the protocol, port, and path properties for
those values respectively).

// don't do this
const options = {
  host: 'http://example.com/path/to/resource',
};

// do this instead
const options = {
  host: 'example.com',
  path: '/path/to/resource',
};

http.request(options, (res) => {});

Check your localhost mapping

If you’re trying to connect to localhost, and the ENOTFOUND error is thrown,
it may mean that the localhost is missing in your hosts file. On Linux and
macOS, ensure that your /etc/hosts file contains the following entry:

You may need to flush your DNS cache afterward:

sudo killall -HUP mDNSResponder # macOS

On Linux, clearing the DNS cache depends on the distribution and caching service
in use. Therefore, do investigate the appropriate command to run on your system.

3. ETIMEDOUT

The ETIMEDOUT error is thrown by the Node.js runtime when a connection or HTTP
request is not closed properly after some time. You might encounter this error
from time to time if you configured a timeout on your
outgoing HTTP requests. The general solution to this issue is to catch the error
and repeat the request, preferably using an
exponential backoff
strategy so that a waiting period is added between subsequent retries until the
request eventually succeeds, or the maximum amount of retries is reached. If you
encounter this error frequently, try to investigate your request timeout
settings and choose a more appropriate value for the endpoint
if possible.

4. ECONNREFUSED

The ECONNREFUSED error is produced when a request is made to an endpoint but a
connection could not be established because the specified address wasn’t
reachable. This is usually caused by an inactive target service. For example,
the error below resulted from attempting to connect to http://localhost:8000
when no program is listening at that endpoint.

Error: connect ECONNREFUSED 127.0.0.1:8000
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
Emitted 'error' event on ClientRequest instance at:
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:526:28)
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -111,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8000
}

The fix for this problem is to ensure that the target service is active and
accepting connections at the specified endpoint.

5. ERRADDRINUSE

This error is commonly encountered when starting or restarting a web server. It
indicates that the server is attempting to listen for connections at a port that
is already occupied by some other application.

Error: listen EADDRINUSE: address already in use :::3001
    at Server.setupListenHandle [as _listen2] (node:net:1330:16)
    at listenInCluster (node:net:1378:12)
    at Server.listen (node:net:1465:7)
    at Function.listen (/home/ayo/dev/demo/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:16:18)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 3001
}

The easiest fix for this error would be to configure your application to listen
on a different port (preferably by updating an environmental variable). However,
if you need that specific port that is in use, you can find out the process ID
of the application using it through the command below:

Output

COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
node    2902  ayo   19u  IPv6 781904      0t0  TCP *:3001 (LISTEN)

Afterward, kill the process by passing the PID value to the kill command:

After running the command above, the application will be forcefully closed
freeing up the desired port for your intended use.

6. EADDRNOTAVAIL

This error is similar to EADDRINUSE because it results from trying to run a
Node.js server at a specific port. It usually indicates a configuration issue
with your IP address, such as when you try to bind your server to a static IP:

const express = require('express');
const app = express();

const server = app.listen(3000, '192.168.0.101', function () {
  console.log('server listening at port 3000......');
});

Output

Error: listen EADDRNOTAVAIL: address not available 192.168.0.101:3000
    at Server.setupListenHandle [as _listen2] (node:net:1313:21)
    at listenInCluster (node:net:1378:12)
    at doListen (node:net:1516:7)
    at processTicksAndRejections (node:internal/process/task_queues:84:21)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1357:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EADDRNOTAVAIL',
  errno: -99,
  syscall: 'listen',
  address: '192.168.0.101',
  port: 3000
}

To resolve this issue, ensure that you have the right IP address (it may
sometimes change), or you can bind to any or all IPs by using 0.0.0.0 as shown
below:

var server = app.listen(3000, '0.0.0.0', function () {
  console.log('server listening at port 3000......');
});

7. ECONNABORTED

The ECONNABORTED exception is thrown when an active network connection is
aborted by the server before reading from the request body or writing to the
response body has completed. The example below demonstrates how this problem can
occur in a Node.js program:

const express = require('express');
const app = express();
const path = require('path');

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
  });
  res.end();
});

const server = app.listen(3000, () => {
  console.log('server listening at port 3001......');
});

Output

Error: Request aborted
    at onaborted (/home/ayo/dev/demo/node_modules/express/lib/response.js:1030:15)
    at Immediate._onImmediate (/home/ayo/dev/demo/node_modules/express/lib/response.js:1072:9)
    at processImmediate (node:internal/timers:466:21) {
  code: 'ECONNABORTED'
}

The problem here is that res.end() was called prematurely before
res.sendFile() has had a chance to complete due to the asynchronous nature of
the method. The solution here is to move res.end() into sendFile()‘s
callback function:

app.get('/', function (req, res, next) {
  res.sendFile(path.join(__dirname, 'new.txt'), null, (err) => {
    console.log(err);
    res.end();
  });
});

8. EHOSTUNREACH

An EHOSTUNREACH exception indicates that a TCP connection failed because the
underlying protocol software found no route to the network or host. It can also
be triggered when traffic is blocked by a firewall or in response to information
received by intermediate gateways or switching nodes. If you encounter this
error, you may need to check your operating system’s routing tables or firewall
setup to fix the problem.

9. EAI_AGAIN

Node.js throws an EAI_AGAIN error when a temporary failure in domain name
resolution occurs. A DNS lookup timeout that usually indicates a problem with
your network connection or your proxy settings. You can get this error when
trying to install an npm package:

Output

npm ERR! code EAI_AGAIN
npm ERR! syscall getaddrinfo
npm ERR! errno EAI_AGAIN
npm ERR! request to https://registry.npmjs.org/nestjs failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org

If you’ve determined that your internet connection is working correctly, then
you should investigate your DNS resolver settings (/etc/resolv.conf) or your
/etc/hosts file to ensure it is set up correctly.

10. ENOENT

This error is a straightforward one. It means «Error No Entity» and is raised
when a specified path (file or directory) does not exist in the filesystem. It
is most commonly encountered when performing an operation with the fs module
or running a script that expects a specific directory structure.

fs.open('non-existent-file.txt', (err, fd) => {
  if (err) {
    console.log(err);
  }
});

Output

[Error: ENOENT: no such file or directory, open 'non-existent-file.txt'] {
  errno: -2,
  code: 'ENOENT',
  syscall: 'open',
  path: 'non-existent-file.txt'
}

To fix this error, you either need to create the expected directory structure or
change the path so that the script looks in the correct directory.

11. EISDIR

If you encounter this error, the operation that raised it expected a file
argument but was provided with a directory.

// config is actually a directory
fs.readFile('config', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EISDIR: illegal operation on a directory, read] {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}

Fixing this error involves correcting the provided path so that it leads to a
file instead.

12. ENOTDIR

This error is the inverse of EISDIR. It means a file argument was supplied
where a directory was expected. To avoid this error, ensure that the provided
path leads to a directory and not a file.

fs.opendir('/etc/passwd', (err, _dir) => {
  if (err) throw err;
});

Output

[Error: ENOTDIR: not a directory, opendir '/etc/passwd'] {
  errno: -20,
  code: 'ENOTDIR',
  syscall: 'opendir',
  path: '/etc/passwd'
}

13. EACCES

The EACCES error is often encountered when trying to access a file in a way
that is forbidden by its access permissions. You may also encounter this error
when you’re trying to install a global NPM package (depending on how you
installed Node.js and npm), or when you try to run a server on a port lower
than 1024.

fs.readFile('/etc/sudoers', (err, data) => {
  if (err) throw err;
  console.log(data);
});

Output

[Error: EACCES: permission denied, open '/etc/sudoers'] {
  errno: -13,
  code: 'EACCES',
  syscall: 'open',
  path: '/etc/sudoers'
}

Essentially, this error indicates that the user executing the script does not
have the required permission to access a resource. A quick fix is to prefix the
script execution command with sudo so that it is executed as root, but this is
a bad idea
for security reasons.

The correct fix for this error is to give the user executing the script the
required permissions to access the resource through the chown command on Linux
in the case of a file or directory.

sudo chown -R $(whoami) /path/to/directory

If you encounter an EACCES error when trying to listen on a port lower than
1024, you can use a higher port and set up port forwarding through iptables.
The following command forwards HTTP traffic going to port 80 to port 8080
(assuming your application is listening on port 8080):

sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

If you encounter EACCES errors when trying to install a global npm package,
it usually means that you installed the Node.js and npm versions found in your
system’s repositories. The recommended course of action is to uninstall those
versions and reinstall them through a Node environment manager like
NVM or Volta.

14. EEXIST

The EEXIST error is another filesystem error that is encountered whenever a
file or directory exists, but the attempted operation requires it not to exist.
For example, you will see this error when you attempt to create a directory that
already exists as shown below:

const fs = require('fs');

fs.mkdirSync('temp', (err) => {
  if (err) throw err;
});

Output

Error: EEXIST: file already exists, mkdir 'temp'
    at Object.mkdirSync (node:fs:1349:3)
    at Object.<anonymous> (/home/ayo/dev/demo/main.js:3:4)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47 {
  errno: -17,
  syscall: 'mkdir',
  code: 'EEXIST',
  path: 'temp'
}

The solution here is to check if the path exists through fs.existsSync()
before attempting to create it:

const fs = require('fs');

if (!fs.existsSync('temp')) {
  fs.mkdirSync('temp', (err) => {
    if (err) throw err;
  });
}

15. EPERM

The EPERM error may be encountered in various scenarios, usually when
installing an npm package. It indicates that the operation being carried out
could not be completed due to permission issues. This error often indicates that
a write was attempted to a file that is in a read-only state although you may
sometimes encounter an EACCES error instead.

Here are some possible fixes you can try if you run into this problem:

  1. Close all instances of your editor before rerunning the command (maybe some
    files were locked by the editor).
  2. Clean the npm cache with npm cache clean --force.
  3. Close or disable your Anti-virus software if have one.
  4. If you have a development server running, stop it before executing the
    installation command once again.
  5. Use the --force option as in npm install --force.
  6. Remove your node_modules folder with rm -rf node_modules and install them
    once again with npm install.

Conclusion

In this article, we covered 15 of the most common Node.js errors you are likely
to encounter when developing applications or utilizing Node.js-based tools, and
we discussed possible solutions to each one. This by no means an exhaustive list
so ensure to check out the
Node.js errors documentation or the
errno(3) man page for a
more comprehensive listing.

Thanks for reading, and happy coding!

Check Uptime, Ping, Ports, SSL and more.

Get Slack, SMS and phone incident alerts.

Easy on-call duty scheduling.

Create free status page on your domain.

Got an article suggestion?
Let us know

Share on Twitter

Share on Facebook

Share via e-mail

Next article

How to Configure Nginx as a Reverse Proxy for Node.js Applications

Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Содержание

  1. Error: read ECONNRESET at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) Emitted ‘error’ event on ClientRequest instance. #42154
  2. Comments
  3. Version
  4. Platform
  5. Subsystem
  6. What steps will reproduce the bug?
  7. How often does it reproduce? Is there a required condition?
  8. What is the expected behavior?
  9. What do you see instead?
  10. Additional information
  11. Version
  12. Platform
  13. Subsystem
  14. What steps will reproduce the bug?
  15. How often does it reproduce? Is there a required condition?
  16. What is the expected behavior?
  17. What do you see instead?
  18. Additional information
  19. Version
  20. Platform
  21. Subsystem
  22. What steps will reproduce the bug?
  23. How often does it reproduce? Is there a required condition?
  24. What is the expected behavior?
  25. What do you see instead?
  26. Additional information
  27. Node.js v19.4.0 documentation
  28. Events #
  29. Passing arguments and this to listeners #
  30. Asynchronous vs. synchronous #
  31. Handling events only once #
  32. Error events #
  33. Capture rejections of promises #
  34. Class: EventEmitter #
  35. Event: ‘newListener’ #
  36. Event: ‘removeListener’ #
  37. emitter.addListener(eventName, listener) #
  38. emitter.emit(eventName[, . args]) #
  39. emitter.eventNames() #
  40. emitter.getMaxListeners() #
  41. emitter.listenerCount(eventName) #
  42. emitter.listeners(eventName) #
  43. emitter.off(eventName, listener) #
  44. emitter.on(eventName, listener) #
  45. emitter.once(eventName, listener) #
  46. emitter.prependListener(eventName, listener) #
  47. emitter.prependOnceListener(eventName, listener) #
  48. emitter.removeAllListeners([eventName]) #
  49. emitter.removeListener(eventName, listener) #
  50. emitter.setMaxListeners(n) #
  51. emitter.rawListeners(eventName) #
  52. emitter[Symbol.for(‘nodejs.rejection’)](err, eventName[, . args]) #
  53. events.defaultMaxListeners #
  54. events.errorMonitor #
  55. events.getEventListeners(emitterOrTarget, eventName) #
  56. events.once(emitter, name[, options]) #
  57. Awaiting multiple events emitted on process.nextTick() #
  58. events.captureRejections #
  59. events.captureRejectionSymbol #
  60. events.listenerCount(emitter, eventName) #
  61. events.on(emitter, eventName[, options]) #
  62. events.setMaxListeners(n[, . eventTargets]) #
  63. Class: events.EventEmitterAsyncResource extends EventEmitter #
  64. new events.EventEmitterAsyncResource([options]) #
  65. eventemitterasyncresource.asyncId #
  66. eventemitterasyncresource.asyncResource #
  67. eventemitterasyncresource.emitDestroy() #
  68. eventemitterasyncresource.triggerAsyncId #
  69. EventTarget and Event API #
  70. Node.js EventTarget vs. DOM EventTarget #
  71. NodeEventTarget vs. EventEmitter #
  72. Event listener #
  73. EventTarget error handling #
  74. Class: Event #
  75. Class: EventTarget #

Error: read ECONNRESET at TLSWrap.onStreamRead (node:internal/stream_base_commons:217:20) Emitted ‘error’ event on ClientRequest instance. #42154

Version

Platform

Subsystem

What steps will reproduce the bug?

Sending 1000 TPS request

How often does it reproduce? Is there a required condition?

When TPS increase then, its break and server get restart

What is the expected behavior?

Process getting terminated, in ideal case, it should not terminate the process to stop

What do you see instead?

due to the process break, kubernetes POD getting crash, resulting all that movement in progress requests are getting fail, nd most importly server is not available

Additional information

The text was updated successfully, but these errors were encountered:

Thanks for the report!

What is your code exactly using? https.request ? If that’s the case, stream.finished can be really useful for error handling.

If more data, such as a minimal reproduction case is possible, that will be really helpful.

Below code is use for the Accept the request for customer using HTTP and do process the request, fetch the date from DB and response back.

CODE

Same error here, while trying to retrieve Kubernetes pods logs as stream.

I am getting the same error trying to run webpack :

It’s quite random, sometimes I have to run npm run build 5 times until I don’t get the error. Sometimes it works immediately. Very hard to reproduce.

Tried 16.14.0 as well, same result.

Connection reset is a normal consequence. It can’t be avoided. It means the client left before it last sent packet can be acknowledged (how TCP works). I see them with iPhone clients with short url codes that simply send a 301 status. The client is gone the moment I sent headers, before I can finish the stream. Other times is related to a web app with a service worker that tells the page to stop fetching from the server and instead reload and use cache. HTTP

The problem I’m having is catching all instances of it. I’m getting application crashes with the same -104 . On HTTP2 I’m listening on the sessions as well as the stream. I catch session and stream errors with ECONNRESET. But somewhere, somehow, it’s slipping through the cracks.

I’ve tried sessionError and it’s mostly the same. I still get crashes. My guess is the the socket itself is getting a connection resetting somewhere after the session is closed, or before any session is negotiated.

I’m on v16.14.0 on Linux. Considering the crashes are so random and I get uncaughtException for origin in the ‘uncaughtException’ event, I’m ready to just ignore it there, despite it being so dangerous. I don’t know where lines L06-L11 are coming from. It might be the pm2 module exporting that.

Edit: Same result with this.http2Server.addListener(‘connection’, (socket) => socket.on(‘error’, console.error)) . This is happening with the same three URLs again and again. It seems to be at the tail end of the session. Maybe it’s related to the SSE I use.

I made more progress with clientError handler, but it’s still not stopping the crash:

I gave up. I’ve tried every error watcher I can think up and had to resort to:

Unless I’m missing one, there’s a leak somewhere.

Edit: I added ‘sessionError’ and upgraded to v16.14.2 . Let’s see how it goes.

Hi I was also having the same problem. found a few causes I get these responses in node V14, V16 and V17. I hope this can help anyone solve their problems in the future

Client Connection Error [Error: 140232514893760:error:1417A0C1:SSL routines:tls_post_process_client_hello:no shared cipher. /deps/openssl/openssl/ssl/statem/statem_srvr.c:2313: ] < library: ‘SSL routines’, function: ‘tls_post_process_client_hello’, reason: ‘no shared cipher’, code: ‘ERR_SSL_NO_SHARED_CIPHER’ >Client Connection Error Client Connection Error [Error: 140232514893760:error:142090FC:SSL routines:tls_early_post_process_client_hello:unknown protocol. /deps/openssl/openssl/ssl/statem/statem_srvr.c:1689: ] < library: ‘SSL routines’, function: ‘tls_early_post_process_client_hello’, reason: ‘unknown protocol’, code: ‘ERR_SSL_UNKNOWN_PROTOCOL’ >Client Connection Error Client Connection Error [Error: 140232514893760:error:14209102:SSL routines:tls_early_post_process_client_hello:unsupported protocol. /deps/openssl/openssl/ssl/statem/statem_srvr.c:1714:] < library: ‘SSL routines’, function: ‘tls_early_post_process_client_hello’, reason: ‘unsupported protocol’, code: ‘ERR_SSL_UNSUPPORTED_PROTOCOL’ >Client Connection Error Client Connection Error Error: socket hang up at connResetException (node:internal/errors:691:14) at TLSSocket.onSocketClose (node:_tls_wrap:1080:23) at TLSSocket.emit (node:events:538:35) at node:net:687:12 at Socket.done (node:_tls_wrap:580:7) at Object.onceWrapper (node:events:646:26) at Socket.emit (node:events:526:28) at TCP. (node:net:687:12)

I was able to solve all my leaks with the following:

  • Connection timeout: this.http2Server.setTimeout(120_000);
  • Client Error Handler: this.http2Server.addListener(‘clientError’, (err, socket) => socket.destroy(err));
  • Session Error Handler: this.http2Server.addListener(‘sessionError’, (err, session) => socket.destroy(err));
  • Session Timeout handler: this.http2Server.addListener(‘session’, (session) => session.setTimeout(60_000, () => session.destroy(new Error(‘TIMEOUT’)))
  • Stream Error handler: this.http2Server.addListener(‘stream’, (stream) => stream.addListener(‘error’, (err) => stream.destroy(err)));

(not exactly my code, but should handle all cases and leave no leaks)

Upgrading Node to 16.15 from 16.14 solved the issue for us.

Specifically it was happening on webpack start.

Hi team,
Need help on this issue. My application was deployed in GKE (Google Cloud Project) and seeing the below error

read ECONNRESET
at TLSWrap.onStreamRead (internal/stream_base_commons.js:209:20)

I am using the https call module and this happens only when there is connecting from external vendor api which is not internal network and I don’t see this issue when there is internal applications with in the network.

Currently I am using the Node version in my docker file as14.15.0. So based on the above comments I see this is an bug in Node V14 in other forum. I just want to check is this fix on Node V16 LTS version

Upgrading Node to 16.15 from 16.14 solved the issue for us.

Specifically it was happening on webpack start.

@meznaric I am facing this issue while calling the https call from my GKE application to external vendor API. Yesterday I upgraded my node js version from 14 —> 16.15.1 but still see the error. could you please let me know which version of minor version of Node V16 resolved you..

Version

Platform

Subsystem

What steps will reproduce the bug?

Sending 1000 TPS request

How often does it reproduce? Is there a required condition?

When TPS increase then, its break and server get restart

What is the expected behavior?

Process getting terminated, in ideal case, it should not terminate the process to stop

What do you see instead?

due to the process break, kubernetes POD getting crash, resulting all that movement in progress requests are getting fail, nd most importly server is not available

Additional information

Version

Platform

Subsystem

What steps will reproduce the bug?

Sending 1000 TPS request

How often does it reproduce? Is there a required condition?

When TPS increase then, its break and server get restart

What is the expected behavior?

Process getting terminated, in ideal case, it should not terminate the process to stop

What do you see instead?

due to the process break, kubernetes POD getting crash, resulting all that movement in progress requests are getting fail, nd most importly server is not available

Additional information

@jaiswarvipin Is this issue resolved for you? If yes could you please let me know how it got fix and I am facing the same

I’m having the same issue 🗡️ The nodejs version doesn’t matter, I used nvm and tried a bunch of them.

Same issue here. With (18.3.0, 17.4.0, 16.14.0, 16.15.0) only 15.9.0 not cause this issue.

I’am starting react app with babel.

Use node package manager like n and downgrade node to 15.9.0 temporary helps me.

Again, this isn’t a Node issue. If you don’t add a catch for client errors, your app will crash whenever a client doesn’t close a connection cleanly. I’ve been running with the logic in #42154 (comment) for over a month with public servers without anymore crashes or memory leaks. (Though I did add a session.ping() to each session to force timeouts to fire and prevent leaks.)

Best of luck to you guys implementing the error catchers. And even more luck to those of you that don’t. 😆

could you please let me know which version of minor version of Node V16 resolved you..

@gopinaresh we went from 16.14.2 to 16.15.0

Not sure, it probably has multiple causes. My memory is not fresh on this issue, but IIRC upgrade solved the issue on CI and dev machines. I also checked change log of node release and I think something relevant changed (that was the reason why I attempted node upgrade).

@meznaric Share your clienterror catcher code. If you have none, then that’s the problem.

To explain better, connection resets are a normal part of all HTTP client/server connections. It’s just more probable to happen with TLS instead of plaintext.

For example, with HTTP:

  1. Client: Sends GET Request
  2. Server: Receives GET Request and sends back data
  1. Client: Sends sends TLS ClientHello
  2. Server: Receives TLS Hello and sends back TLS ServerHello with certificate information
  3. Client: Acknowledges the TLS information, picks an encryption, and sends its choice
  4. Server: Receives the encryption requests and sends back confirmation
  5. Client: Client receives confirmation and sends GET request
  6. Server: Server receives GET request and sends back data

Even though the connection can drop at any point, with HTTPS (TLS) there are more packets being exchanged. If any point the client decides to leave (aborts request) before the transaction finishes, you’ll get a connection reset. It’s normal. You just have to catch it.

There’s also a SYN/ACK phase that’s part of TCP, but that happens before/during a connection is made. HTTP/3 does away with that by moving to UDP, so HTTP/3 could technically expose more flow interruptions to the user.

Источник

Node.js v19.4.0 documentation

Events #

Source Code: lib/events.js

Much of the Node.js core API is built around an idiomatic asynchronous event-driven architecture in which certain kinds of objects (called «emitters») emit named events that cause Function objects («listeners») to be called.

For instance: a net.Server object emits an event each time a peer connects to it; a fs.ReadStream emits an event when the file is opened; a stream emits an event whenever data is available to be read.

All objects that emit events are instances of the EventEmitter class. These objects expose an eventEmitter.on() function that allows one or more functions to be attached to named events emitted by the object. Typically, event names are camel-cased strings but any valid JavaScript property key can be used.

When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and discarded.

The following example shows a simple EventEmitter instance with a single listener. The eventEmitter.on() method is used to register listeners, while the eventEmitter.emit() method is used to trigger the event.

Passing arguments and this to listeners #

The eventEmitter.emit() method allows an arbitrary set of arguments to be passed to the listener functions. Keep in mind that when an ordinary listener function is called, the standard this keyword is intentionally set to reference the EventEmitter instance to which the listener is attached.

It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the this keyword will no longer reference the EventEmitter instance:

Asynchronous vs. synchronous #

The EventEmitter calls all listeners synchronously in the order in which they were registered. This ensures the proper sequencing of events and helps avoid race conditions and logic errors. When appropriate, listener functions can switch to an asynchronous mode of operation using the setImmediate() or process.nextTick() methods:

Handling events only once #

When a listener is registered using the eventEmitter.on() method, that listener is invoked every time the named event is emitted.

Using the eventEmitter.once() method, it is possible to register a listener that is called at most once for a particular event. Once the event is emitted, the listener is unregistered and then called.

Error events #

When an error occurs within an EventEmitter instance, the typical action is for an ‘error’ event to be emitted. These are treated as special cases within Node.js.

If an EventEmitter does not have at least one listener registered for the ‘error’ event, and an ‘error’ event is emitted, the error is thrown, a stack trace is printed, and the Node.js process exits.

To guard against crashing the Node.js process the domain module can be used. (Note, however, that the node:domain module is deprecated.)

As a best practice, listeners should always be added for the ‘error’ events.

It is possible to monitor ‘error’ events without consuming the emitted error by installing a listener using the symbol events.errorMonitor .

Capture rejections of promises #

Using async functions with event handlers is problematic, because it can lead to an unhandled rejection in case of a thrown exception:

The captureRejections option in the EventEmitter constructor or the global setting change this behavior, installing a .then(undefined, handler) handler on the Promise . This handler routes the exception asynchronously to the Symbol.for(‘nodejs.rejection’) method if there is one, or to ‘error’ event handler if there is none.

Setting events.captureRejections = true will change the default for all new instances of EventEmitter .

The ‘error’ events that are generated by the captureRejections behavior do not have a catch handler to avoid infinite error loops: the recommendation is to not use async functions as ‘error’ event handlers.

Class: EventEmitter #

History

Added captureRejections option.

The EventEmitter class is defined and exposed by the node:events module:

All EventEmitter s emit the event ‘newListener’ when new listeners are added and ‘removeListener’ when existing listeners are removed.

It supports the following option:

Event: ‘newListener’ #

  • eventName | The name of the event being listened for
  • listener The event handler function

The EventEmitter instance will emit its own ‘newListener’ event before a listener is added to its internal array of listeners.

Listeners registered for the ‘newListener’ event are passed the event name and a reference to the listener being added.

The fact that the event is triggered before adding the listener has a subtle but important side effect: any additional listeners registered to the same name within the ‘newListener’ callback are inserted before the listener that is in the process of being added.

Event: ‘removeListener’ #

History

Version Changes
v13.4.0, v12.16.0

For listeners attached using .once() , the listener argument now yields the original listener function.

  • eventName | The event name
  • listener The event handler function

The ‘removeListener’ event is emitted after the listener is removed.

emitter.addListener(eventName, listener) #

Alias for emitter.on(eventName, listener) .

emitter.emit(eventName[, . args]) #

Synchronously calls each of the listeners registered for the event named eventName , in the order they were registered, passing the supplied arguments to each.

Returns true if the event had listeners, false otherwise.

emitter.eventNames() #

Returns an array listing the events for which the emitter has registered listeners. The values in the array are strings or Symbol s.

emitter.getMaxListeners() #

Returns the current max listener value for the EventEmitter which is either set by emitter.setMaxListeners(n) or defaults to events.defaultMaxListeners .

emitter.listenerCount(eventName) #

  • eventName | The name of the event being listened for
  • Returns:

Returns the number of listeners listening to the event named eventName .

emitter.listeners(eventName) #

History

Version Changes
v6.1.0, v4.7.0

For listeners attached using .once() this returns the original listeners instead of wrapper functions now.

Returns a copy of the array of listeners for the event named eventName .

emitter.off(eventName, listener) #

emitter.on(eventName, listener) #

  • eventName | The name of the event.
  • listener The callback function
  • Returns:

Adds the listener function to the end of the listeners array for the event named eventName . No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

Returns a reference to the EventEmitter , so that calls can be chained.

By default, event listeners are invoked in the order they are added. The emitter.prependListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

emitter.once(eventName, listener) #

  • eventName | The name of the event.
  • listener The callback function
  • Returns:

Adds a one-time listener function for the event named eventName . The next time eventName is triggered, this listener is removed and then invoked.

Returns a reference to the EventEmitter , so that calls can be chained.

By default, event listeners are invoked in the order they are added. The emitter.prependOnceListener() method can be used as an alternative to add the event listener to the beginning of the listeners array.

emitter.prependListener(eventName, listener) #

  • eventName | The name of the event.
  • listener The callback function
  • Returns:

Adds the listener function to the beginning of the listeners array for the event named eventName . No checks are made to see if the listener has already been added. Multiple calls passing the same combination of eventName and listener will result in the listener being added, and called, multiple times.

Returns a reference to the EventEmitter , so that calls can be chained.

emitter.prependOnceListener(eventName, listener) #

  • eventName | The name of the event.
  • listener The callback function
  • Returns:

Adds a one-time listener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this listener is removed, and then invoked.

Returns a reference to the EventEmitter , so that calls can be chained.

emitter.removeAllListeners([eventName]) #

Removes all listeners, or those of the specified eventName .

It is bad practice to remove listeners added elsewhere in the code, particularly when the EventEmitter instance was created by some other component or module (e.g. sockets or file streams).

Returns a reference to the EventEmitter , so that calls can be chained.

emitter.removeListener(eventName, listener) #

Removes the specified listener from the listener array for the event named eventName .

removeListener() will remove, at most, one instance of a listener from the listener array. If any single listener has been added multiple times to the listener array for the specified eventName , then removeListener() must be called multiple times to remove each instance.

Once an event is emitted, all listeners attached to it at the time of emitting are called in order. This implies that any removeListener() or removeAllListeners() calls after emitting and before the last listener finishes execution will not remove them from emit() in progress. Subsequent events behave as expected.

Because listeners are managed using an internal array, calling this will change the position indices of any listener registered after the listener being removed. This will not impact the order in which listeners are called, but it means that any copies of the listener array as returned by the emitter.listeners() method will need to be recreated.

When a single function has been added as a handler multiple times for a single event (as in the example below), removeListener() will remove the most recently added instance. In the example the once(‘ping’) listener is removed:

Returns a reference to the EventEmitter , so that calls can be chained.

emitter.setMaxListeners(n) #

By default EventEmitter s will print a warning if more than 10 listeners are added for a particular event. This is a useful default that helps finding memory leaks. The emitter.setMaxListeners() method allows the limit to be modified for this specific EventEmitter instance. The value can be set to Infinity (or 0 ) to indicate an unlimited number of listeners.

Returns a reference to the EventEmitter , so that calls can be chained.

emitter.rawListeners(eventName) #

Returns a copy of the array of listeners for the event named eventName , including any wrappers (such as those created by .once() ).

emitter[Symbol.for(‘nodejs.rejection’)](err, eventName[, . args]) #

History

Version Changes
v7.0.0

No longer experimental.

Added in: v13.4.0, v12.16.0

The Symbol.for(‘nodejs.rejection’) method is called in case a promise rejection happens when emitting an event and captureRejections is enabled on the emitter. It is possible to use events.captureRejectionSymbol in place of Symbol.for(‘nodejs.rejection’) .

events.defaultMaxListeners #

By default, a maximum of 10 listeners can be registered for any single event. This limit can be changed for individual EventEmitter instances using the emitter.setMaxListeners(n) method. To change the default for all EventEmitter instances, the events.defaultMaxListeners property can be used. If this value is not a positive number, a RangeError is thrown.

Take caution when setting the events.defaultMaxListeners because the change affects all EventEmitter instances, including those created before the change is made. However, calling emitter.setMaxListeners(n) still has precedence over events.defaultMaxListeners .

This is not a hard limit. The EventEmitter instance will allow more listeners to be added but will output a trace warning to stderr indicating that a «possible EventEmitter memory leak» has been detected. For any single EventEmitter , the emitter.getMaxListeners() and emitter.setMaxListeners() methods can be used to temporarily avoid this warning:

The —trace-warnings command-line flag can be used to display the stack trace for such warnings.

The emitted warning can be inspected with process.on(‘warning’) and will have the additional emitter , type , and count properties, referring to the event emitter instance, the event’s name and the number of attached listeners, respectively. Its name property is set to ‘MaxListenersExceededWarning’ .

events.errorMonitor #

This symbol shall be used to install a listener for only monitoring ‘error’ events. Listeners installed using this symbol are called before the regular ‘error’ listeners are called.

Installing a listener using this symbol does not change the behavior once an ‘error’ event is emitted. Therefore, the process will still crash if no regular ‘error’ listener is installed.

events.getEventListeners(emitterOrTarget, eventName) #

  • emitterOrTarget |
  • eventName |
  • Returns:

Returns a copy of the array of listeners for the event named eventName .

For EventEmitter s this behaves exactly the same as calling .listeners on the emitter.

For EventTarget s this is the only way to get the event listeners for the event target. This is useful for debugging and diagnostic purposes.

events.once(emitter, name[, options]) #

History

Version Changes
v17.4.0, v16.14.0

The signal option is supported now.

Added in: v11.13.0, v10.16.0

  • emitter
  • name
  • options
    • signal Can be used to cancel waiting for the event.
  • Returns:

    Creates a Promise that is fulfilled when the EventEmitter emits the given event or that is rejected if the EventEmitter emits ‘error’ while waiting. The Promise will resolve with an array of all the arguments emitted to the given event.

    This method is intentionally generic and works with the web platform EventTarget interface, which has no special ‘error’ event semantics and does not listen to the ‘error’ event.

    The special handling of the ‘error’ event is only used when events.once() is used to wait for another event. If events.once() is used to wait for the ‘ error’ event itself, then it is treated as any other kind of event without special handling:

    Awaiting multiple events emitted on process.nextTick() #

    There is an edge case worth noting when using the events.once() function to await multiple events emitted on in the same batch of process.nextTick() operations, or whenever multiple events are emitted synchronously. Specifically, because the process.nextTick() queue is drained before the Promise microtask queue, and because EventEmitter emits all events synchronously, it is possible for events.once() to miss an event.

    To catch both events, create each of the Promises before awaiting either of them, then it becomes possible to use Promise.all() , Promise.race() , or Promise.allSettled() :

    events.captureRejections #

    History

Version Changes
v15.0.0

No longer experimental.

Added in: v13.4.0, v12.16.0

Change the default captureRejections option on all new EventEmitter objects.

events.captureRejectionSymbol #

History

Version Changes
v17.4.0, v16.14.0

No longer experimental.

Added in: v13.4.0, v12.16.0

See how to write a custom rejection handler.

events.listenerCount(emitter, eventName) #

  • emitter The emitter to query
  • eventName | The event name

A class method that returns the number of listeners for the given eventName registered on the given emitter .

events.on(emitter, eventName[, options]) #

  • emitter
  • eventName | The name of the event being listened for
  • options
    • signal Can be used to cancel awaiting events.
  • Returns: that iterates eventName events emitted by the emitter

Returns an AsyncIterator that iterates eventName events. It will throw if the EventEmitter emits ‘error’ . It removes all listeners when exiting the loop. The value returned by each iteration is an array composed of the emitted event arguments.

events.setMaxListeners(n[, . eventTargets]) #

  • n A non-negative number. The maximum number of listeners per EventTarget event.
  • . eventsTargets | Zero or more or instances. If none are specified, n is set as the default max for all newly created and objects.

Class: events.EventEmitterAsyncResource extends EventEmitter #

The EventEmitterAsyncResource class has the same methods and takes the same options as EventEmitter and AsyncResource themselves.

new events.EventEmitterAsyncResource([options]) #

  • options
    • captureRejections It enables automatic capturing of promise rejection. Default: false .
    • name The type of async event. Default::new.target.name .
    • triggerAsyncId The ID of the execution context that created this async event. Default: executionAsyncId() .
    • requireManualDestroy If set to true , disables emitDestroy when the object is garbage collected. This usually does not need to be set (even if emitDestroy is called manually), unless the resource’s asyncId is retrieved and the sensitive API’s emitDestroy is called with it. When set to false , the emitDestroy call on garbage collection will only take place if there is at least one active destroy hook. Default: false .

eventemitterasyncresource.asyncId #

  • Type: The unique asyncId assigned to the resource.

eventemitterasyncresource.asyncResource #

The returned AsyncResource object has an additional eventEmitter property that provides a reference to this EventEmitterAsyncResource .

eventemitterasyncresource.emitDestroy() #

Call all destroy hooks. This should only ever be called once. An error will be thrown if it is called more than once. This must be manually called. If the resource is left to be collected by the GC then the destroy hooks will never be called.

eventemitterasyncresource.triggerAsyncId #

  • Type: The same triggerAsyncId that is passed to the AsyncResource constructor.

EventTarget and Event API #

History

Version Changes
v17.4.0, v16.14.0

changed EventTarget error handling.

No longer experimental.

The EventTarget and Event classes are now available as globals.

The EventTarget and Event objects are a Node.js-specific implementation of the EventTarget Web API that are exposed by some Node.js core APIs.

Node.js EventTarget vs. DOM EventTarget #

There are two key differences between the Node.js EventTarget and the EventTarget Web API:

  1. Whereas DOM EventTarget instances may be hierarchical, there is no concept of hierarchy and event propagation in Node.js. That is, an event dispatched to an EventTarget does not propagate through a hierarchy of nested target objects that may each have their own set of handlers for the event.
  2. In the Node.js EventTarget , if an event listener is an async function or returns a Promise , and the returned Promise rejects, the rejection is automatically captured and handled the same way as a listener that throws synchronously (see EventTarget error handling for details).

NodeEventTarget vs. EventEmitter #

The NodeEventTarget object implements a modified subset of the EventEmitter API that allows it to closely emulate an EventEmitter in certain situations. A NodeEventTarget is not an instance of EventEmitter and cannot be used in place of an EventEmitter in most cases.

  1. Unlike EventEmitter , any given listener can be registered at most once per event type . Attempts to register a listener multiple times are ignored.
  2. The NodeEventTarget does not emulate the full EventEmitter API. Specifically the prependListener() , prependOnceListener() , rawListeners() , setMaxListeners() , getMaxListeners() , and errorMonitor APIs are not emulated. The ‘newListener’ and ‘removeListener’ events will also not be emitted.
  3. The NodeEventTarget does not implement any special default behavior for events with type ‘error’ .
  4. The NodeEventTarget supports EventListener objects as well as functions as handlers for all event types.

Event listener #

Event listeners registered for an event type may either be JavaScript functions or objects with a handleEvent property whose value is a function.

In either case, the handler function is invoked with the event argument passed to the eventTarget.dispatchEvent() function.

Async functions may be used as event listeners. If an async handler function rejects, the rejection is captured and handled as described in EventTarget error handling.

An error thrown by one handler function does not prevent the other handlers from being invoked.

The return value of a handler function is ignored.

Handlers are always invoked in the order they were added.

Handler functions may mutate the event object.

EventTarget error handling #

When a registered event listener throws (or returns a Promise that rejects), by default the error is treated as an uncaught exception on process.nextTick() . This means uncaught exceptions in EventTarget s will terminate the Node.js process by default.

Throwing within an event listener will not stop the other registered handlers from being invoked.

The EventTarget does not implement any special default handling for ‘error’ type events like EventEmitter .

Currently errors are first forwarded to the process.on(‘error’) event before reaching process.on(‘uncaughtException’) . This behavior is deprecated and will change in a future release to align EventTarget with other Node.js APIs. Any code relying on the process.on(‘error’) event should be aligned with the new behavior.

Class: Event #

History

Version Changes
v16.0.0

The Event class is now available through the global object.

The Event object is an adaptation of the Event Web API. Instances are created internally by Node.js.

event.bubbles #

This is not used in Node.js and is provided purely for completeness.

event.cancelBubble() #

Alias for event.stopPropagation() . This is not used in Node.js and is provided purely for completeness.

event.cancelable #
  • Type: True if the event was created with the cancelable option.
event.composed #

This is not used in Node.js and is provided purely for completeness.

event.composedPath() #

Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness.

event.currentTarget #
  • Type: The EventTarget dispatching the event.

Alias for event.target .

event.defaultPrevented #

Is true if cancelable is true and event.preventDefault() has been called.

event.eventPhase #
  • Type: Returns 0 while an event is not being dispatched, 2 while it is being dispatched.

This is not used in Node.js and is provided purely for completeness.

event.isTrusted #
event.preventDefault() #

Sets the defaultPrevented property to true if cancelable is true .

event.returnValue #
  • Type: True if the event has not been canceled.

This is not used in Node.js and is provided purely for completeness.

event.srcElement #
  • Type: The EventTarget dispatching the event.

Alias for event.target .

event.stopImmediatePropagation() #

Stops the invocation of event listeners after the current one completes.

event.stopPropagation() #

This is not used in Node.js and is provided purely for completeness.

event.target #
  • Type: The EventTarget dispatching the event.
event.timeStamp #

The millisecond timestamp when the Event object was created.

event.type #

The event type identifier.

Class: EventTarget #

History

Version Changes
v15.0.0

The EventTarget class is now available through the global object.

eventTarget.addEventListener(type, listener[, options]) #

History

Version Changes
v15.0.0

add support for signal option.

  • type
  • listener |
  • options
    • once When true , the listener is automatically removed when it is first invoked. Default: false .
    • passive When true , serves as a hint that the listener will not call the Event object’s preventDefault() method. Default: false .
    • capture Not directly used by Node.js. Added for API completeness. Default: false .
    • signal The listener will be removed when the given AbortSignal object’s abort() method is called.

Adds a new handler for the type event. Any given listener is added only once per type and per capture option value.

If the once option is true , the listener is removed after the next time a type event is dispatched.

The capture option is not used by Node.js in any functional way other than tracking registered event listeners per the EventTarget specification. Specifically, the capture option is used as part of the key when registering a listener . Any individual listener may be added once with capture = false , and once with capture = true .

eventTarget.dispatchEvent(event) #
  • event
  • Returns: true if either event’s cancelable attribute value is false or its preventDefault() method was not invoked, otherwise false .

Dispatches the event to the list of handlers for event.type .

The registered event listeners is synchronously invoked in the order they were registered.

eventTarget.removeEventListener(type, listener[, options]) #
  • type
  • listener |
  • options
    • capture

Removes the listener from the list of handlers for event type .

Источник

Adblock
detector

Version Changes
v15.4.0

Cover image for Fixing nodemon 'Error: listen EADDRINUSE: address in use'

Matt Heindel

Matt Heindel

Posted on Jul 8, 2021

• Updated on Jul 12, 2021

Has this ever happened to you?

You go to start up your server with npm start and you get the below error message

$ npm start

> cruddy-todos@1.0.0 start /home/mc_heindel/HackReactor/hr-rfp54-cruddy-todo
> npx nodemon ./server.js

[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node ./server.js`
events.js:292
      throw er; // Unhandled 'error' event
      ^

Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (net.js:1318:16)
    at listenInCluster (net.js:1366:12)
    at Server.listen (net.js:1452:7)
    at Function.listen (/home/mc_heindel/HackReactor/hr-rfp54-cruddy-todo/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/mc_heindel/HackReactor/hr-rfp54-cruddy-todo/server.js:79:5)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1345:8)
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: 'EADDRINUSE',
  errno: -98,
  syscall: 'listen',
  address: '::',
  port: 3000
}
[nodemon] app crashed - waiting for file changes before starting...

Enter fullscreen mode

Exit fullscreen mode

Luckily there is a solution!

This error occurs when a process is already running on the port you’re trying to use. All you need to do is kill that process. In this case, since the port we want to use is 3000 we could simply paste and execute the below code in our terminal.

kill -9 $(lsof -t -i:3000)

Enter fullscreen mode

Exit fullscreen mode

This will kill the process running on port 3000 and you should be good to start your server with npm start like usual.

Save this command for future use

If this happens often, it’s a great idea to add an alias to bash for reuse anytime. The below code is a function that accepts a port number to kill and when saved can be reused for any port number.

killport() { kill -9 $(lsof -t -i:"$@"); } # kill process on specified port number

Enter fullscreen mode

Exit fullscreen mode

The quick and easy way to save

Simply execute the below command and the killport function will be available every time you open bash. Just remember to restart your terminal for the saved function to be loaded after first adding it.

echo 'killport() { kill -9 $(lsof -t -i:"$@"); } # kill process on specified port number' >> ~/.bashrc

Enter fullscreen mode

Exit fullscreen mode

Below is an example of how the newly defined killport function can be used to kill a process on port 3000.

killport 3000

Enter fullscreen mode

Exit fullscreen mode

The slightly more advanced way to save

To save this function alongside your other bash aliases and configurations you just need to add the below code to ~/.bashrc or ~/.bash_aliases which can be accomplished using vim ~/.bashrc and pasting in the code snippet.

killport() { kill -9 $(lsof -t -i:"$@"); } # kill process on specified port number

Enter fullscreen mode

Exit fullscreen mode

Below code is use for the Accept the request for customer using HTTP and do process the request, fetch the date from DB and response back.

CODE

const httpServer 			= require('http');

/* Set connection keep alive */
httpServer.globalAgent.keepAlive = true;

httpServer.createServer((request, response) => {
	try{
		response.setHeader('Content-Type', 'text/plain');

	       response.setTimeout(parseInt(process.env.DEFAULT_API_REQUEST_TIME_OUT), function (_pConnectionTimeOut) {
			/* Send response */
			sendResponse(response, responseObj.HTTP_STATUS.REQUESTTIMEOUT, responseObj.ERROR_CODES.SERVICE_TIME_OUT, responseObj.ERROR.TYPE.REQUESTTIMEOUT, responseObj.MESSAGES.DEFAULT.REQUESTTIMEOUT);
		});

		let strEndPoint = urlObj.parse(request.url, true).pathname;

		let body = "";
		request.on('error', (err) => {
			console.log("Request error")
			console.log(err)
			request.destroy();
			response.end();
		}).on('socket',function (socket) {
			socket.on('timeout', function() {
				request.destroy();
				/* Send response */
				sendResponse(response, responseObj.HTTP_STATUS.REQUESTTIMEOUT, responseObj.ERROR_CODES.SERVICE_TIME_OUT, responseObj.ERROR.TYPE.REQUESTTIMEOUT, responseObj.MESSAGES.DEFAULT.REQUESTTIMEOUT);
			});
		}).on('data', (chunk) => {
			body += chunk.toString()
		}).on('end', () => {
			/* Validating and upstreating the requst */
                        console.log(Body);
                        /* Setting response headers */
  		response.statusCode = 200;
		/* writing the message into the writer buffer */
		await response.write(JSON.stringify({"responsebody":body}));
		/* Flusing the message closing the communation */
		response.end();
		});
	}catch(exception){
		console.log("===================HTTP OBJECT ERROR===============")
		console.log(exception);
		console.log("===================HTTP OBJECT ERROR===============")
	}
/* on client conention error */
}).on("clientError",function(err,socket){
	console.log("Client Connection Error ");
	console.log(err);
	console.log("Client Connection Error");
	/* On client connection error */
}).on("secureConnection",function(socket){
	console.log("secure Connection Error ");
	/* On client connection error */
}).listen(9091);

node.js express permission error on linux

using arch with admin user account and no sudo on this script:

var express = require('express');

var fs = require('fs');

var app = express();
app.get('/lol', function(req, res) {
    res.sendFile('second.html', {root: __dirname })
});
var port = process.env.PORT || 81;
var server = app.listen(port);

i get this error that didnt change when i changed the port or the url to trigger it
it instantly gives me this error after i run the command: node site.js
(the code above is site.js)

    node:events:371
      throw er; // Unhandled 'error' event
      ^

Error: listen EACCES: permission denied 0.0.0.0:81
    at Server.setupListenHandle [as _listen2] (node:net:1302:21)
    at listenInCluster (node:net:1367:12)
    at Server.listen (node:net:1454:7)
    at Function.listen (/home/{name}/node_modules/express/lib/application.js:618:24)
    at Object.<anonymous> (/home/{name}/Documents/web/demo/site.js:10:18)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
Emitted 'error' event on Server instance at:
    at emitErrorNT (node:net:1346:8)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  code: 'EACCES',
  errno: -13,
  syscall: 'listen',
  address: '0.0.0.0',
  port: 81
}

if i run the script with sudo it works fine but i dont want to run it in sudo
beacuse i have to run it on a server with no sudo. any help?

Advertisement

Answer

Using port below 1024 without root permission is common issue. Try port bigger than 1024.

8 People found this is helpful

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Emitted error event on childprocess instance at
  • Emex 3 критическая ошибка
  • Embedded flash sd card the ahs file system mount failed with i o error
  • Embedded flash sd card error reading media 0 physical block 2 timeout
  • Embed video cannot be played как исправить

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии