Ошибка connect econnrefused

I am new to node and running into this error on a simple tutorial.

I am on the OS X 10.8.2 trying this from CodeRunner and the Terminal.
I have also tried putting my module in the node_modules folder.

I can tell this is some kind of connection problem but I have no idea why?

events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: connect ECONNREFUSED
    at errnoException (net.js:770:11)
    at Object.afterConnect [as oncomplete] (net.js:761:19)

app.js:

var makeRequest = require('./make_request');

makeRequest("Here's looking at you, kid");
makeRequest("Hello, this is dog");

make_request.js:

var http = require('http');

var makeRequest = function(message) {

    //var message = "Here's looking at you, kid.";
    var options = {
        host: 'localhost', port: 8080, path:'/', method: 'POST'
    }

    var request = http.request(options, function(response) {
        response.on('data', function(data) {
            console.log(data);
        });
    });
    request.write(message);
    request.end();
};

module.exports = makeRequest;

asked Jan 5, 2013 at 3:59

ian's user avatar

5

Chances are you are struggling with the node.js dying whenever the server you are calling refuses to connect. Try this:

process.on('uncaughtException', function (err) {
    console.log(err);
}); 

This keeps your server running and also give you a place to attach the debugger and look for a deeper problem.

answered Nov 5, 2013 at 16:23

user2957009's user avatar

user2957009user2957009

8736 silver badges10 bronze badges

3

You’re trying to connect to localhost:8080 … is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

answered Mar 23, 2013 at 11:38

JakubKnejzlik's user avatar

JakubKnejzlikJakubKnejzlik

6,3633 gold badges40 silver badges41 bronze badges

I was having the same issue with ghost and heroku.

heroku config:set NODE_ENV=production 

solved it!

Check your config and env that the server is running on.

Dan's user avatar

Dan

5,1634 gold badges31 silver badges42 bronze badges

answered Feb 23, 2014 at 5:09

Siddhartha Mukherjee's user avatar

2

I just had this problem happen to me and after some searching for an answer I have found this other stackoverflow thread: ECONNREFUSED error with node.js that does not occur in other clients

The solution provided there, worked for me like a charm, it seems nodeJS has some issues accessing localhost dns, however switching to 127.0.0.1 works perfectly fine.

answered Jun 27, 2022 at 19:05

Vladimir Lazar's user avatar

2

If you are on MEAN (Mongo-Express-AngularJS-Node) stack, run mongod first, and this error message will go away.

answered May 17, 2016 at 14:29

Bob Vargas's user avatar

Bob VargasBob Vargas

1312 silver badges6 bronze badges

1

You need to have a server running on port 8080 when you run the code above that simply returns the request back through the response. Copy the code below to a separate file (say ‘server.js’) and start this server using the node command (node server.js). You can then separately run your code above (node app.js) from a separate command line.

var http = require('http');

http.createServer(function(request, response){

    //The following code will print out the incoming request text
    request.pipe(response);

}).listen(8080, '127.0.0.1');

console.log('Listening on port 8080...');

answered Jan 16, 2016 at 21:45

Andrew M.'s user avatar

Andrew M.Andrew M.

811 silver badge7 bronze badges

Sometimes it may occur, if there is any database connection in your code but you did not start the database server yet.

Im my case i have some piece of code to connect with mongodb

mongoose.connect("mongodb://localhost:27017/demoDb");

after i started the mongodb server with the command mongod this error is gone

answered Feb 26, 2016 at 19:22

pashaplus's user avatar

pashapluspashaplus

3,6062 gold badges26 silver badges25 bronze badges

ECONNREFUSED error means that connection could not be made with the target service (in your case localhost:8080). Check your service running on port 8080.

To know more about node.js errors, refer this doc.

answered Jul 26, 2021 at 12:45

Yuvaraj Anbarasan's user avatar

People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:

ps aux | grep node

This will print something along the lines of:

user    7668  4.3  1.0  42060 10708 pts/1    Sl+  20:36   0:00 node server
user    7749  0.0  0.0   4384   832 pts/8    S+   20:37   0:00 grep --color=auto node

In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668.

answered Jan 5, 2013 at 4:38

rahulmehta95's user avatar

1

If you are using NodeJs version > 17, try to downgrade to use NodeJs 16.
On 17, by default, the debugger bind IP is on IPv6, and sometimes you IDE might not be able to attach to it

answered Sep 15, 2022 at 13:36

Steven Shi's user avatar

Steven ShiSteven Shi

1,0321 gold badge10 silver badges10 bronze badges

Check with starting mysql in terminal. Use below command

mysql-ctl start

In my case its worked

answered Jun 25, 2015 at 12:36

mujaffars's user avatar

mujaffarsmujaffars

1,3952 gold badges15 silver badges35 bronze badges

Run server.js from a different command line and client.js from a different command line

answered Jun 11, 2019 at 5:50

shamila's user avatar

shamilashamila

1,2806 gold badges20 silver badges45 bronze badges

For me it was a problem in library node-agent-base v4.x which was requested by https-proxy-agent which in it’s side was requested by newrelic v5.x library.

The problem was that node-agent-base v4.x for some marvellous idea decided to patch core https.get request (You can see this in the file patch-core.js in the repo). And when I used library which use https.get, it was failed because node-agent-base v4.x have changed function signature, which gave me request to 127.0.0.1 as initial url was lost…

I’ve fixed this by updating to the next version of newrelic 6.x, where node-agent-base v4.x doesn’t has such ‘patches’.

This is just crazy…hope my response will save you some time, I’ve spent several days to debug this.

answered Jan 31, 2022 at 11:15

KorbenDallas's user avatar

In NodeJs version > 17, the debugger bind IP is on IPv6, so first you should map your IP to IPv6 then use that in your program.

answered Jun 24 at 12:31

Hamid Reza Sedigh's user avatar

The Unhandled 'error' event is referring not providing a function to the request to pass errors. Without this event the node process ends with the error instead of failing gracefully and providing actual feedback. You can set the event just before the request.write line to catch any issues:

request.on('error', function(err)
{
    console.log(err);
});

More examples below:

https://nodejs.org/api/http.html#http_http_request_options_callback

answered Mar 17, 2016 at 22:25

SmujMaiku's user avatar

SmujMaikuSmujMaiku

6036 silver badges10 bronze badges

Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.

answered Oct 14, 2020 at 16:26

Ricardo Mitchell's user avatar

In my case I forget to npm start the node app

answered Sep 11, 2022 at 22:01

Muhammad Javed Baloch's user avatar

For me this happened when my .env file was named incorrectly to .env.local

answered Nov 30, 2022 at 19:26

Alistair St Pierre's user avatar

1

The name provided to Docker is the hostname to use when connecting to that host. For example, if your service is named «couchdb» you could access it from another container like «curl couchdb:5984».

https://docs.docker.com/compose/networking/

When you run docker compose up, the following happens:

  1. A network called myapp_default is created.
  2. A container is created using web’s configuration. It joins the network myapp_default under the name web.
  3. A container is created using db’s configuration. It joins the network myapp_default under the name db.

answered Jun 5 at 19:34

Ronnie Royston's user avatar

Ronnie RoystonRonnie Royston

16.9k6 gold badges78 silver badges92 bronze badges

I was having the same issue in my dev env with Postman when checking the API.
I searched literally all the answers came from google, but no avail.

SOLUTION:
I have just moved to «insomnia» (an alternative to Postman) and it works just fine. Hope this workaround may help.

answered Nov 24, 2021 at 13:48

E. Djalalov's user avatar

Время на прочтение
2 мин

Количество просмотров 46K

Вы тоже столкнулись с ошибкой ECONNREFUSED — connection refused by server в FileZilla? Тогда здорово, что вы нашли это руководство. Я покажу вам три метода, как можно исправить эту ошибку FTP.

Первый Метод. Изменение Дефолтного Значения Порта FileZilla

Причиной ошибки может быть неправильный порт при подключении через FileZilla. В этой ситуации вам просто нужно изменить порт FTP по умолчанию на дефолтный номер порта SFTP. Просто измените 21 на 22 в поле ввода “Port”.

Второй Метод. Отключение Антивируса/Брандмауэра

Иногда эта ошибка может возникать, когда антивирусное программное обеспечение и/или брандмауэр отказывает FileZilla в попытках установить соединение.

В случае, если антивирус или брандмауэр вызывает ECONNREFUSED, вам нужно просто отключить это ПО, а затем снова подключиться. Сначала я покажу вам, как это сделать в macOS:

  • Нажмите на иконку “Apple” в верхнем меню. Перейдите в “System Preferences”.
  • Найдите раздел настроек “Security & Privacy”.

  • Перейдите во вкладку “Firewall” и выберите “Turn Off Firewall”.

Если вы используете Windows, выполните следующие действия:

  • В строке поиска по Windows введите запрос “Control Panel”.
  • Затем перейдите в раздел “System & Security” и найдите “Windows Defender Firewall”.

  • В меню слева найдите “Turn Windows Defender Firewall on or off”.

  • Измените параметры, чтобы отключить брандмауэр Защитника Windows для общедоступных и частных сетей в следующем окне и нажмите “Ok”.

Подробней о том, как деактивировать разное антивирусное программное обеспечение можно прочитать здесь (англ).

Если отключение антивируса или брандмауэра не помогло и вы по-прежнему получаете ошибку «ECONNREFUSED — connection refused by server», попробуйте следующий метод.

Третий Метод. Изменение Мастера Настройки Сети FileZilla

Что делать, если предыдущие решения не принесли желаемого результата? Чтобы исправить ошибку, вы также можете попробовать изменить конфигурации сети FileZilla:

  • Подключитесь к FTP-клиенту FileZilla, затем перейдите в “Edit” и выберите “Network Configuration Wizard”.

  • Когда появится окно “Firewall and router configuration wizard”, нажмите “Next”, чтобы продолжить.
  • В качестве режима передачи по умолчанию выберите “Passive (recommended)”. Также отметьте галочкой “Allow fallback to another transfer mode on failure”.

  • Выберите “Use server’s external IP address instead”.
  • Выберите “Get the external IP address from the following URL”. Введите значение по умолчанию в случае, если поле ввода не заполнено (значение по умолчанию — это URL ip.filezilla-project.org/ip.php), нажмите “Next”, чтобы продолжить.
  • Не изменяйте настройки диапазона портов, просто выберите “Ask operating system for a port” и нажмите “Next”.

На этом этапе вам необходимо убедиться, что все настройки были выполнены правильно. Нажмите кнопку “Test”, чтобы FileZilla попыталась установить соединение с probe.filezilla-project.org. Программа выполнит несколько простых тестов.

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

Выводы

Вот и все. Это и есть три метода, как исправить ошибку «ECONNREFUSED — connection refused by server». Надеемся, что один из них таки поможет вам решить проблему с FileZilla. Если у вас остались вопросы или вы знаете другие решения, не стесняйтесь оставить комментарий!

I am new to node and running into this error on a simple tutorial.

I am on the OS X 10.8.2 trying this from CodeRunner and the Terminal.
I have also tried putting my module in the node_modules folder.

I can tell this is some kind of connection problem but I have no idea why?

events.js:71
        throw arguments[1]; // Unhandled 'error' event
                       ^
Error: connect ECONNREFUSED
    at errnoException (net.js:770:11)
    at Object.afterConnect [as oncomplete] (net.js:761:19)

app.js:

var makeRequest = require('./make_request');

makeRequest("Here's looking at you, kid");
makeRequest("Hello, this is dog");

make_request.js:

var http = require('http');

var makeRequest = function(message) {

    //var message = "Here's looking at you, kid.";
    var options = {
        host: 'localhost', port: 8080, path:'/', method: 'POST'
    }

    var request = http.request(options, function(response) {
        response.on('data', function(data) {
            console.log(data);
        });
    });
    request.write(message);
    request.end();
};

module.exports = makeRequest;

asked Jan 5, 2013 at 3:59

ian's user avatar

5

Chances are you are struggling with the node.js dying whenever the server you are calling refuses to connect. Try this:

process.on('uncaughtException', function (err) {
    console.log(err);
}); 

This keeps your server running and also give you a place to attach the debugger and look for a deeper problem.

answered Nov 5, 2013 at 16:23

user2957009's user avatar

user2957009user2957009

8736 silver badges10 bronze badges

3

You’re trying to connect to localhost:8080 … is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

answered Mar 23, 2013 at 11:38

JakubKnejzlik's user avatar

JakubKnejzlikJakubKnejzlik

6,3633 gold badges40 silver badges41 bronze badges

I was having the same issue with ghost and heroku.

heroku config:set NODE_ENV=production 

solved it!

Check your config and env that the server is running on.

Dan's user avatar

Dan

5,1634 gold badges31 silver badges42 bronze badges

answered Feb 23, 2014 at 5:09

Siddhartha Mukherjee's user avatar

2

I just had this problem happen to me and after some searching for an answer I have found this other stackoverflow thread: ECONNREFUSED error with node.js that does not occur in other clients

The solution provided there, worked for me like a charm, it seems nodeJS has some issues accessing localhost dns, however switching to 127.0.0.1 works perfectly fine.

answered Jun 27, 2022 at 19:05

Vladimir Lazar's user avatar

2

If you are on MEAN (Mongo-Express-AngularJS-Node) stack, run mongod first, and this error message will go away.

answered May 17, 2016 at 14:29

Bob Vargas's user avatar

Bob VargasBob Vargas

1312 silver badges6 bronze badges

1

You need to have a server running on port 8080 when you run the code above that simply returns the request back through the response. Copy the code below to a separate file (say ‘server.js’) and start this server using the node command (node server.js). You can then separately run your code above (node app.js) from a separate command line.

var http = require('http');

http.createServer(function(request, response){

    //The following code will print out the incoming request text
    request.pipe(response);

}).listen(8080, '127.0.0.1');

console.log('Listening on port 8080...');

answered Jan 16, 2016 at 21:45

Andrew M.'s user avatar

Andrew M.Andrew M.

811 silver badge7 bronze badges

Sometimes it may occur, if there is any database connection in your code but you did not start the database server yet.

Im my case i have some piece of code to connect with mongodb

mongoose.connect("mongodb://localhost:27017/demoDb");

after i started the mongodb server with the command mongod this error is gone

answered Feb 26, 2016 at 19:22

pashaplus's user avatar

pashapluspashaplus

3,6062 gold badges26 silver badges25 bronze badges

ECONNREFUSED error means that connection could not be made with the target service (in your case localhost:8080). Check your service running on port 8080.

To know more about node.js errors, refer this doc.

answered Jul 26, 2021 at 12:45

Yuvaraj Anbarasan's user avatar

People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:

ps aux | grep node

This will print something along the lines of:

user    7668  4.3  1.0  42060 10708 pts/1    Sl+  20:36   0:00 node server
user    7749  0.0  0.0   4384   832 pts/8    S+   20:37   0:00 grep --color=auto node

In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668.

answered Jan 5, 2013 at 4:38

rahulmehta95's user avatar

1

If you are using NodeJs version > 17, try to downgrade to use NodeJs 16.
On 17, by default, the debugger bind IP is on IPv6, and sometimes you IDE might not be able to attach to it

answered Sep 15, 2022 at 13:36

Steven Shi's user avatar

Steven ShiSteven Shi

1,0321 gold badge10 silver badges10 bronze badges

Check with starting mysql in terminal. Use below command

mysql-ctl start

In my case its worked

answered Jun 25, 2015 at 12:36

mujaffars's user avatar

mujaffarsmujaffars

1,3952 gold badges15 silver badges35 bronze badges

Run server.js from a different command line and client.js from a different command line

answered Jun 11, 2019 at 5:50

shamila's user avatar

shamilashamila

1,2806 gold badges20 silver badges45 bronze badges

For me it was a problem in library node-agent-base v4.x which was requested by https-proxy-agent which in it’s side was requested by newrelic v5.x library.

The problem was that node-agent-base v4.x for some marvellous idea decided to patch core https.get request (You can see this in the file patch-core.js in the repo). And when I used library which use https.get, it was failed because node-agent-base v4.x have changed function signature, which gave me request to 127.0.0.1 as initial url was lost…

I’ve fixed this by updating to the next version of newrelic 6.x, where node-agent-base v4.x doesn’t has such ‘patches’.

This is just crazy…hope my response will save you some time, I’ve spent several days to debug this.

answered Jan 31, 2022 at 11:15

KorbenDallas's user avatar

In NodeJs version > 17, the debugger bind IP is on IPv6, so first you should map your IP to IPv6 then use that in your program.

answered Jun 24 at 12:31

Hamid Reza Sedigh's user avatar

The Unhandled 'error' event is referring not providing a function to the request to pass errors. Without this event the node process ends with the error instead of failing gracefully and providing actual feedback. You can set the event just before the request.write line to catch any issues:

request.on('error', function(err)
{
    console.log(err);
});

More examples below:

https://nodejs.org/api/http.html#http_http_request_options_callback

answered Mar 17, 2016 at 22:25

SmujMaiku's user avatar

SmujMaikuSmujMaiku

6036 silver badges10 bronze badges

Had a similar issue, it turned out the listening port printed was different from what it actually was. Typos in the request string or listening function might make the target server appear to not exist.

answered Oct 14, 2020 at 16:26

Ricardo Mitchell's user avatar

In my case I forget to npm start the node app

answered Sep 11, 2022 at 22:01

Muhammad Javed Baloch's user avatar

For me this happened when my .env file was named incorrectly to .env.local

answered Nov 30, 2022 at 19:26

Alistair St Pierre's user avatar

1

The name provided to Docker is the hostname to use when connecting to that host. For example, if your service is named «couchdb» you could access it from another container like «curl couchdb:5984».

https://docs.docker.com/compose/networking/

When you run docker compose up, the following happens:

  1. A network called myapp_default is created.
  2. A container is created using web’s configuration. It joins the network myapp_default under the name web.
  3. A container is created using db’s configuration. It joins the network myapp_default under the name db.

answered Jun 5 at 19:34

Ronnie Royston's user avatar

Ronnie RoystonRonnie Royston

16.9k6 gold badges78 silver badges92 bronze badges

I was having the same issue in my dev env with Postman when checking the API.
I searched literally all the answers came from google, but no avail.

SOLUTION:
I have just moved to «insomnia» (an alternative to Postman) and it works just fine. Hope this workaround may help.

answered Nov 24, 2021 at 13:48

E. Djalalov's user avatar

Jul 27, 2023

Edvinas B.

3min Read

If you encounter the ECONNREFUSED – connection refused by a server error in FileZilla and need help fixing it, you’ve come to the right place. This tutorial will guide you through several methods to resolve the FTP error. Let’s get started!

Error code ECONNREFUSED
Error type FTP
Error variations Connection attempt failed with “econnrefused – connection refused by server”.
Error: connect econnrefused
Error causes Firewall configurations
Anti-virus configurations
Using incorrect port
Incorrect Filezilla configurations

How to Fix SSH Connection Refused Error Video Guide

Learn how to fix the SSH Connection Refused error using three simple methods in this video tutorial.

youtube channel logo

Subscribe For more educational videos!
Hostinger Academy

Method 1 – Disabling Firewall/Anti-Virus Software on Your Computer

One of the possible reasons for this error is that the firewall and anti-virus software on your computer is preventing FileZilla from making a connection.

If that’s the cause of the Error: Connect econnrefused – connection refused by server error, simply disable the firewall and anti-virus software on your computer and try to reconnect. Here’s how to do so on Windows:

  1. Press the Windows key on your keyboard and type in Control Panel.
  2. Head to System and Security and locate Windows Defender Firewall.This image shows you the System and Security on Windows.
  3. On the left menu bar, find the option to Turn Windows Defender Firewall on or off.This image shows you windows defender firewall settings on Windows to fix the ECONNREFUSED - connection refused by server error.
  4. On the next window, modify the settings to turn off Windows Defender Firewall for public and private networks, then press Ok.

On macOS, you need to:

  1. Click on the Apple menu on the upper left toolbar, then System Preferences.
  2. Locate the Security & Privacy option.this image shows you the system preferences settings on MacOs
  3. Switch to Firewall and click on the Turn Off Firewall option.This image shows you how to turn off firewall on macOs

To disable different anti-virus software on your computers, check out this article for detailed guidance.

That’s it! This method should fix the ECONNREFUSED – connection refused by server error instantly if your computers’ firewall and anti-virus are the problems. Should it persists, turn everything back on and do the next method instead.

Method 2- Changing FileZilla’s Default Port Value

How to change port number on FileZilla to fix the ECONNREFUSED - connection refused by server error

Sometimes, the error happens because you’re using the wrong port when connecting with FileZilla. If that’s the case, all you need to do is put 22 (default SFTP port) instead of 21 (default FTP port number) on the port column, as seen below.

Important! Make sure to edit the Site Manager’s configuration and change the protocol to SFTP – SSH File Transfer Protocol if you’re using port 22.

Method 3 – Editing FileZilla’s Network Configuration Wizard

If none of the solutions above work, try editing FileZilla’s network configurations to fix the ECONNREFUSED – connection refused by server error. To access the Network Configuration Manager, here’s what you need to do:

  1.  Connect to FileZilla FTP client and head to Edit -> Network Configuration Wizard.This image shows you how to find the network configuration wizard in FileZilla
  2. Press Next to proceed once a Firewall and router configuration wizard window pop out.
  3. Choose Passive (recommended) as the Default transfer mode, and put a check on the Allow fallback to another transfer mode on failure option.This image shows you how to edit firewall and configuration wizard in FileZilla
  4. Select Use the server’s external IP address instead.
  5. Choose the Get the external IP address from the following URL. If the input field is blank, enter the default value, which is http://ip.filezilla-project.org/ip.php, and proceed.
  6. Don’t make any changes to the port range configuration and select Ask operating system for a port.

Now you just need to make sure everything is configured correctly. Click on the Test button, and FileZilla will try to connect to probe.filezilla-project.org to perform some simple tests.

If you don’t receive any errors during the test, try connecting to your hosting account again, and you should connect just fine. If the ECONNREFUSED – connection refused by server error still appears, contact your hosting customer support team for assistance.

Conclusion

By finishing this short tutorial, you’ve learned how to fix the FileZilla Error: Connect econnrefused – connection refused by server error through three simple methods. Here’s a quick recap of the reasons why it happens and how to fix it:

  • Computers’ anti-virus software and firewall preventing FileZilla from making a connection – turn them off temporarily on your computers.
  • Using the wrong port when making a connection – Use SFTP default number port (22) instead of the FTP port (21)
  • Misconfiguration in your FileZilla Client – editing the configurations through FileZilla’s Network Configurations Wizard.

Simple, right? If you have any other solutions, or if you have any questions, do let us know in the comments!

Author

Edvinas is a professional mentor and trainer of customer support agents. When he’s not teaching the secrets of providing exceptional service, he likes to travel the world and play basketball.

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:

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:

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:

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......');
});
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......');
});
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:

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);
  }
});
[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);
});
[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;
});
[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);
});
[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;
});
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!

Author's avatar

Article by

Ayooluwa Isaiah

Ayo is the Head of Content at Better Stack. His passion is simplifying and communicating complex technical ideas effectively. His work was featured on several esteemed publications including LWN.net, Digital Ocean, and CSS-Tricks. When he’s not writing or coding, he loves to travel, bike, and play tennis.

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

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.

Понравилась статья? Поделить с друзьями:
  • Ошибка config pck
  • Ошибка could not load localization txt
  • Ошибка crc 0hscan op com
  • Ошибка concrt140 dll что делать windows 10
  • Ошибка cpu экскаватор