Error listen eaddrinuse code eaddrinuse errno eaddrinuse syscall listen

If I run a server with the port 80, and I try to use XMLHttpRequest I am getting this error: Error: listen EADDRINUSE Why is it problem for NodeJS, if I want to do a request, while I run a server o...

The aforementioned killall -9 node, suggested by Patrick works as expected and solves the problem but you may want to read the edit part of this very answer about why kill -9 may not be the best way to do it.

On top of that you might want to target a single process rather than blindly killing all active processes.

In that case, first get the process ID (PID) of the process running on that port (say 8888):

lsof -i tcp:8888

This will return something like:

COMMAND   PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node     57385   You   11u  IPv6 0xac745b2749fd2be3      0t0  TCP *:ddi-tcp-1 (LISTEN)

Then just do (ps — actually do not. Please keep reading below):

kill -9 57385

You can read a bit more about this here.

EDIT: I was reading on a fairly related topic today and stumbled upon this interesting thread on why should i not kill -9 a process.

Generally, you should use kill -15 before kill -9 to give the target process a chance to clean up after itself. (Processes can’t catch or ignore SIGKILL, but they can and often do catch SIGTERM.) If you don’t give the process a chance to finish what it’s doing and clean up, it may leave corrupted files (or other state) around that it won’t be able to understand once restarted.

So, as stated you should better kill the above process with:

kill -15 57385

EDIT 2: As noted in a comment around here many times this error is a consequence of not exiting a process gracefully. That means, a lot of people exit a node command (or any other) using CTRL+Z. The correct way of stopping a running process is issuing the CTRL+C command which performs a clean exit.

Exiting a process the right way will free up that port while shutting down. This will allow you to restart the process without going through the trouble of killing it yourself before being able to re-run it again.

In this tutorial, we are going to learn about how to solve the Error: listen EADDRINUSE: address already in use in Node.js.

When we run a development server of react or other apps, sometimes we will see the following error in our terminal.

Error: listen EADDRINUSE: address already in use 127.0.0.1:3000
    at Server.setupListenHandle [as _listen2] (net.js:1306:16)
    at listenInCluster (net.js:1354:12)
    at GetAddrInfoReqWrap.doListen [as callback] (net.js:1493:7)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:65:10)
Emitted 'error' event on Server instance at:
    at emitErrorNT (net.js:1333:8)
    at processTicksAndRejections (internal/process/task_queues.js:81:21) {
  code: 'EADDRINUSE',
  errno: 'EADDRINUSE',
  syscall: 'listen',
  address: '127.0.0.1',
  port: 3000
}

This error tells us, the port number we are trying to run a server is already in use.

To solve this error, we need to close the program that is using this port or try to use a different port.

If you don’t know, which program is using that port then you can use the following command to kill the all node processes currently running.

This quick article shows you how to solve a common error you might confront when working with Node.js.

The Problem

When developing a Node.js application (with Express.js), I sometimes fall into the following problem:

Error: listen EADDRINUSE: address already in use :::3000

Full error message:

Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1380:16)
    at listenInCluster (node:net:1428:12)
    at Server.listen (node:net:1516:7)
    at Function.listen (/Users/goodman/Desktop/Projects/kindacode/api/node_modules/express/lib/application.js:635:24)
    at server (/Users/goodman/Desktop/Projects/kindacode/api/src/index.ts:60:7)
    at bootstrap (/Users/goodman/Desktop/Projects/kindacode/api/src/index.ts:73:3)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 'EADDRINUSE',
  errno: -48,
  syscall: 'listen',
  address: '::',
  port: 3000
}

The console message indicates that I am trying to run my app with a port being used by some program. This happens after my app crashes. Behind the scene, it’s very likely that there is a terminal window hiding out in the background that is still running the app. If you encounter the same problem as mine, don’t panic. Below is the solution.

The Solution

What we have to do is really simple: kill the process that is running on the port. Execute the command below:

npx kill-port 3000

If you need to free a port other than 3000, run the command above on that port. It’s also possible to terminate multiple ports at once:

npx kill-port 3000 4000 5000 6000 7000

Another solution that can solve this problem, as well as many others, is just restarting your computer (you even don’t have to do that in this situation).

That’s it. Further reading:

  • Node.js: Turn a Relative Path into an Absolute Path
  • Nodemon: Automatically Restart a Node.js App on Crash
  • 2 Ways to Set Default Time Zone in Node.js
  • 7 Best Open-Source HTTP Request Libraries for Node.js
  • Node.js: Use Async Imports (Dynamic Imports) with ES Modules

You can also check out our Node.js category page for the latest tutorials and examples.

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

I came across variants of this issue many times without ever being able to replicate it deterministically. But on all cases, I have found that…

  • Killing the port-process ${port} on the nodemon events start, restart or crash, does not solve my problem.
  • Synchronously killing it right before calling .listen(...) on my express app does not solve my problem.
  • However, asynchronously killing it before calling .listen(...) in a .then() does solve my problem, when…
    • …either fuser -k ${port}/tcp and npx kill-port ${port} is used to kill the port-process.
    • …the nodemon restart is delayed (hint: to delay it, merge your current nodemon.json with {delay: ${milliseconds}}). I have the solution below running almost all of the times with {delay: "500"}.

I have written a brief code snippet that does the job of killing the conflicting port-process at run-time, using fuser. I don’t think adapting the code so as to use npx kill-port ${port} would be very hard: I would appreciate if anyone could augment my code with that adaptation :)

Basically, one call of killPort keeps killing all the port-processes that hold onto the port ${port} until no processes are left. Finally, an interval is set so that if a round of killPort has killed any process, it checks again after some time. This killing and re-killing was done because for some reason the conflicting port-processes would get killed once but the error EADDRINUSE would still show up. It may be overkill, pun intended, but to be honest, it works, and I’m happy because of that.

Here it is, along with my current use case and its output:

import {execSync} from 'child_process';

const buildKillPortPromise = (port: number) => new Promise(
    (resolve) => {
      const killPort = () => {
        let hasKilled = false;
        while (true) {
          const pid = execSync(
              `fuser -k ${port}/tcp || echo '---'`, // fuser exits with 1 when no process has been killed
              {stdio: ['ignore', 'pipe', 'ignore']}, // https://nodejs.org/api/child_process.html#child_process_options_stdio
          ).toString().trim();
          if (pid !== '---') {
            hasKilled = true;
            console.log(`PID ${pid} was holding onto port ${port}. It was killed.`);
          } else {
            return hasKilled;
          }
        };
      };
      const intervalId = setInterval(() => {
        if (!killPort()) {
          clearInterval(intervalId);
          resolve(undefined);
        }
      }, 500); // this is the minimum that I have found that works consistently
    },
);

Use case:

export class HttpEntrypoint {
  // ...
  start(): Promise<void> {
    return this.setup() // this.app.use(morgan('combined')) and other stuff
        .then(() => buildKillPortPromise(this.config.port))
        .then(
            () => new Promise(
                (resolve) => {
                  this.server = this.app.listen(
                      this.config.port,
                      () => resolve(undefined),
                  );
                },
            ),
        )
        // .then(() => console.log(`Started listening at ${port}`));
        // ^ this goes outside of this class:
        // await entrypoint.start().then(() => console.log(...))
  }
}

Output:

> nodemon

[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): src/**/*
[nodemon] watching extensions: ts
[nodemon] starting `ts-node src/index.ts`
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19286 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19391 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19485 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19663 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19834 was holding onto port 8420. It was killed.
Started listening on 8420
[nodemon] restarting due to changes...
[nodemon] starting `ts-node src/index.ts`
PID 19942 was holding onto port 8420. It was killed.
Started listening on 8420

Вышеупомянутый killall -9 node, предложенный Патриком, работает так, как ожидалось, и решает проблему, но вы можете прочитать часть редактирования этого самого ответа о том, почему kill -9 может быть не лучшим способом сделать это.

Кроме того, вы можете настроить таргетинг на одиночный процесс, а не слепо убивать активные все.

В этом случае сначала получите идентификатор процесса (PID) процесса, запущенного на этом порту (скажем, 8888):

lsof -i tcp:8888

Это вернет что-то вроде:

COMMAND   PID    USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node     57385   You   11u  IPv6 0xac745b2749fd2be3      0t0  TCP *:ddi-tcp-1 (LISTEN)

Тогда просто сделайте (ps — на самом деле не. Пожалуйста, продолжайте читать ниже):

kill -9 57385

Вы можете прочитать немного об этом здесь.

РЕДАКТИРОВАТЬ: Я читал по довольно смежной теме сегодня и наткнулся на этот интересный поток на почему я не kill -9 процесс.

Как правило, вы должны использовать kill -15 до kill -9, чтобы дать целевому процессу возможность очистить после себя. (Процессы не могут поймать или игнорировать SIGKILL, но они могут и часто блокировать SIGTERM.) Если вы не дадите процессу возможность закончить то, что он делает и очистит, он может оставить поврежденные файлы (или другое состояние) вокруг что он не сможет разобраться после перезапуска.

Итак, как сказано, вам лучше убить описанный выше процесс:

kill -15 57385

РЕДАКТИРОВАТЬ 2: как отмеченный в комментарии здесь, эта ошибка является следствием не изящного выхода из процесса. Это означает, что многие люди выходят из команды node (или любой другой), используя CTRL + Z. Правильный способ остановки запущенного процесса — выдать команду CTRL + C, которая выполняет чистый выход.

Выход из процесса правильным способом освободит этот порт при выключении. Это позволит вам перезапустить процесс, не переживая проблемы с его убийством, прежде чем сможет снова запустить его.

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.

Error Description:

  • If we run a server with the port 80, and we try to use xmlHTTPrequest we get this error: Error: listen EADDRINUSE
  • The server is:
  net.createServer(function (socket) {
    socket.name = socket.remoteAddress + ":" + socket.remotePort;
    console.log('connection request from: ' + socket.remoteAddress);
    socket.destroy();
  }).listen(options.port);
 
click below button to copy the code. By — nodejs tutorial — team

And the request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function() {
    sys.puts("State: " + this.readyState);

    if (this.readyState == 4) {
        sys.puts("Complete.nBody length: " + this.responseText.length);
        sys.puts("Body:n" + this.responseText);
    }
};

xhr.open("GET", "http://mywebsite.com");
xhr.send();
 
click below button to copy the code. By — nodejs tutorial — team

Solution 1:

  • EADDRINUSE means that the port number which listen() tries to bind the server to is already in use.
  • So, in your case, there must be running a server on port 80 already.
  • If you have another webserver running on this port you have to put node.js behind that server and proxy it through it.
  • You should check for the listening event like this, to see if the server is really listening:
var http=require('http');

var server=http.createServer(function(req,res){
    res.end('test');
});

server.on('listening',function(){
    console.log('ok, server is running');
});
server.listen(80);

 
click below button to copy the code. By — nodejs tutorial — team

Solution 2:

  • The killall -9 node, works as expected and solves the problem but you may want to read the answer about why kill -9 may not be the best way to do it.
  • On top of that you might want to target a single process rather than blindly killing all active processes.
  • In that case, first get the process ID (PID) of the process running on that port (say 8888):
lsof -i tcp:8888 
 
click below button to copy the code. By — nodejs tutorial — team
  • This will return something like:

COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME

  • kill -9 57385
  • Then just do kill -9 57385

Solution 3:

  • Skype will sometimes listen on port 80 and therefore cause this error if you try to listen on port 80 from Node.js or any other app.
  • You can turn off that behaviour in Skype by accessing the options and clicking Advanced -> Connection -> Use port 80 (Untick this)

Solution 4:

  • You should try killing the process that is listening on port 80.
  • Killall will kill all the node apps running. You might not want to do that. With this command you can kill only the one app that is listening on a known port.
  • If using unix try this command:
sudo fuser -k 80/tcp    
 
click below button to copy the code. By — nodejs tutorial — team

Solution 5:

  • Simply close the terminal and open a new terminal and run
node server.js
 
click below button to copy the code. By — nodejs tutorial — team

In this post we are going to discuss about how to solve Node.js error: listen EADDRINUSE. EADDRINUSE actually means that the port number which you are binding to the server using listen() is already in use.

Lets say you are creating a http server using the below code where you are binding the port number 8080 to the server.

var http = require(‘http’);
var requestListener = function (request, response) {
  response.writeHead(200, {‘Content-Type’: ‘text/plain’});
  response.end(‘Hello Youn’);
}
var server = http.createServer(requestListener);
server.listen(8080);

If any application is already running on 8080 then you will get the below error (Error: listen EADDRINUSE).

You can check using netstat -an that is there any process running on 8080 or not. If there will be any process running on 8080 you will see something like below when you run command netstat -an in Command Prompt.

To solve this error either you start your node server on another port or close the program using that port. So you can kill the 8080 process or start server on 8081.

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

Понравилась статья? Поделить с друзьями:
  • Error listen eaddrinuse address already in use 3001
  • Error listen eaddrinuse address already in use 3000 ubuntu
  • Error listen eacces permission denied
  • Error list was not declared in this scope
  • Error list visual studio