Error listen eaddrinuse address already in use 8080

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.

Содержание

  1. Coding Defined
  2. a blog for those who code
  3. Saturday, 19 September 2015
  4. How to solve nodejs Error: listen EADDRINUSE
  5. How to kill server when seeing “EADDRINUSE: address already in use”
  6. The Problem
  7. The cause behind this issue
  8. Solution
  9. Kill the process manually
  10. For Mac/Linux
  11. For Windows
  12. Enjoy!
  13. Level Up Coding
  14. Fixing nodemon ‘Error: listen EADDRINUSE: address in use’
  15. Has this ever happened to you?
  16. Luckily there is a solution!
  17. Save this command for future use
  18. The quick and easy way to save
  19. The slightly more advanced way to save
  20. [nodemon] Error: listen EADDRINUSE: address already in use #676
  21. Comments
  22. Node/Экспресс: EADDRINUSE, адрес уже используется — Kill server
  23. ОТВЕТЫ
  24. Ответ 1
  25. Ответ 2
  26. Ответ 3
  27. Ответ 4
  28. Ответ 5
  29. Ответ 6
  30. Ответ 7
  31. Ответ 8
  32. Linux
  33. Windows
  34. Ответ 9
  35. Ответ 10
  36. Ответ 11
  37. Ответ 12
  38. Ответ 13
  39. Ответ 14
  40. Ответ 15
  41. Ответ 16
  42. Ответ 17
  43. Ответ 18
  44. Ответ 19
  45. Ответ 20
  46. Ответ 21
  47. Ответ 22
  48. Ответ 23
  49. Ответ 24
  50. Ответ 25
  51. Ответ 26
  52. Ответ 27
  53. Ответ 28
  54. Ответ 29
  55. Ответ 30

Coding Defined

a blog for those who code

Saturday, 19 September 2015

How to solve nodejs Error: listen EADDRINUSE

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.

Источник

How to kill server when seeing “EADDRINUSE: address already in use”

A tutorial on how to kill the process manually when “EADDRINUSE” happens on Mac/Linux and Windows.

The Problem

When trying to restart a Node application, the previous one did not shut down properly, and you may see a “ listen EADDRINUSE: address already in use” error such as:

The cause behind this issue

The reason behind this is that

process.on(‘exit’, . ) isn’t called when the process crashes or is killed. It is only called when the event loop ends, and since server.close() sort of ends the event loop (it still has to wait for currently running stacks here and there) it makes no sense to put that inside the exit event.

Solution

The proper fix for the application would be

  • On crash, do process.on(‘uncaughtException’, ..)
  • And on kill do process.on(‘SIGTERM’, ..)

When this EADDRINUSE issue has already happened, in order to resolve it, you need to kill the process manually. In order to do that, you need to find the process id (PID) of the process. You know the process is occupying a particular port on your machine or server.

Kill the process manually

For Mac/Linux

To find the process id (PID) associated with the port

Then to kill the process

Use -9 option to make sure the process dies immediately

If you get permissions errors, you may need to use the sudo keyword, for example:

For Windows

Solution 1: Task Manager

Open the Task Manager application ( taskman.exe), from either the Processes or Services tab sort by the PID column. To display the PID column, right-click the header row and select PID from the list. Right-click the process you want to stop and select End task.

Solution 2: Use Command prompt

Open a CMD window in Administrator mode by navigating to Start > Run > type cmd > right-click Command Prompt, then select Run as administrator.

Use the netstat command lists all the active ports. The -a switch displays all ports in use, not just the ports associated with the current user. The -n option stops a hostname lookup (which takes a long time). The -o option lists the process ID that is responsible for the port activity. The findstr command matches the header row that contains the PID string, and the port you are looking for, in a port format with the preceding colon, is :3000.

To kill this process (the /f is force):

Enjoy!

And that’s about it. Thanks for reading

Level Up Coding

Thanks for being a part of our community! Level Up is transforming tech recruiting. Find your perfect job at the best companies.

Источник

Fixing nodemon ‘Error: listen EADDRINUSE: address in use’

Has this ever happened to you?

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

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.

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.

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.

Exit fullscreen mode

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

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

/.bash_aliases which can be accomplished using vim

/.bashrc and pasting in the code snippet.

Источник

[nodemon] Error: listen EADDRINUSE: address already in use #676

I’m running into an error in nodemon today, which only happens with esm using -r from the CLI. Here’s a dead-simple reproduction:

When I run yarn dev from the terminal, and then do Ctrl+S in app.js in the editor, I get

You can see that the app boots correctly, but as soon as any file changes, nodemon can’t restart it. In the meantime, the app still continues to run in the background. If I do Ctrl+C , it quits, but there’s no more process on port 3000 , so killing it by port fuser -k 3000/tcp doesn’t do anything.

  • it works without esm , i.e. if I change «dev»: «nodemon -r esm app» to «dev»: «nodemon app» , the error goes away, and nodemon restarts correctly
  • it works with esm using require(«esm»)(module) syntax instead of -r
  • it works either way without express or any web server (because the port is not used)
  • same issue on Node 11.2.0 , 11.1.0 , and 10.13.0

Tried rebooting, reinstalling Node, removing yarn.lock , then removing and re-installing node_modules , locking to older versions of esm , nodemon , and express . I’m out of options here.

At first, I thought this was nodemon ‘s fault, so I scavenged many threads with this error, but to no avail. Then I noticed that the error appears to be emitted from esm , so I thought I’d post here. Sorry, if I’m posting in a wrong repo; it seems the culprit lies in this library. Any clues are appreciated!

  • OS: Ubuntu 18.10 cosmic
  • Node: 11.2.0 (other versions too, see above)
  • npm: 6.4.1
  • yarn: 1.12.3

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

Источник

Node/Экспресс: EADDRINUSE, адрес уже используется — Kill server

У меня есть простой сервер, работающий в node.js, используя connect:

В моем коде у меня есть фактические обработчики, но это основная идея. Проблема, которую я получаю, —

Я получаю эту ошибку при повторном запуске приложения после того, как он был ранее разбит или ошибки. Поскольку я не открываю новый экземпляр терминала, я закрываю процесс с помощью ctr + z .

Я уверен, что все, что мне нужно сделать, это закрыть сервер или соединение. Я пробовал звонить server.close() в process.on(‘exit’, . ); без везения.

ОТВЕТЫ

Ответ 1

process.on(‘exit’, ..) не вызывается, если процесс вылетает или уничтожается. Он вызывается только тогда, когда цикл события заканчивается, и поскольку server.close() завершает цикл события (он все еще должен ждать текущих стеков здесь и там), нет смысла помещать это внутри события exit.

В случае сбоя, сделайте process.on(‘uncaughtException’, ..) и на kill do process.on(‘SIGTERM’, ..)

При этом SIGTERM (сигнал об отключении по умолчанию) позволяет очищать приложение, а SIGKILL (немедленное завершение) не позволит приложению ничего делать.

Ответ 2

Вы также можете перейти по маршруту командной строки:

чтобы получить идентификаторы процесса.

Выполнение -9 на kill отправляет SIGKILL (вместо SIGTERM). SIGTERM для меня иногда игнорировался node.

Ответ 3

Я нашел для меня самый быстрый способ разрешить это:

Ответ 4

Я ударил это на своем ноутбуке, работающем с win8. это сработало.

Запустите cmd.exe как «Администратор»:

Ответ 5

Сначала вы хотели бы знать, какой процесс использует port 3000

в этом списке будет отображаться все PID, прослушивающие этот порт, как только у вас есть PID, вы можете его завершить следующим образом:

Ответ 6

Проверьте идентификатор PID, то есть идентификатор процесса, запущенного на порту 3000, с помощью команды ниже:

Он выводит что-то вроде следующего:

Теперь убейте процесс, используя:

Ответ 7

Я нашел это решение, попробуйте дать разрешение на использование sudo

Ответ 8

Linux

Запустите ps и определите PID вашего процесса узла.

Затем запустите sudo kill PID

Windows

Используйте список задач для отображения списка запущенных процессов:

Затем завершите процесс узла следующим образом (используя PID, полученный из команды tasklist ):

Ответ 9

Я получал эту ошибку один раз и использовал многие из этих подходов.

Мои проблемы состояли в том, что у меня было два вызова app.listen(3000); в том же app.js script. Первый app.listen() преуспел там, где второй сбросил ошибку.

Еще одна полезная команда, с которой я столкнулся, помогла мне отладить sudo fuser -k 3000/tcp , которая убьет любые запущенные процессы, которые вы могли бы запустить (некоторые процессы могут перезагружаться, например, если они запускаются с forever.js, но это было полезно для меня).

Ответ 10

Вот один вкладыш (замените 3000 на порт или переменную конфигурации):

Ответ 11

Для окон откройте диспетчер задач и найдите процессы node.exe. Убейте их всех с помощью End Task.

Ответ 12

FYI, вы можете убить процесс в одной команде sudo fuser -k 3000/tcp . Это можно сделать для всех других портов, таких как 8000, 8080 или 9000, которые обычно используются для разработки.

Ответ 13

Ответ 14

если вы используете Mac или Linux, вы можете попробовать эту команду на терминале

Ответ 15

Сначала узнайте, что работает, используя:

Вы получите что-то вроде:

Затем вы можете убить процесс следующим образом:

Тогда вы сможете работать без ошибок EADDRINUSE: 3000 listen

Ответ 16

Диспетчер задач (ctrl + alt + del) →

выберите «node.exe» и нажмите «Завершить процесс»

Ответ 17

Для Visual Studio Noobs, как я

Возможно, вы запускаете процесс в других терминалах!

После закрытия терминала в Visual Studio терминал просто исчезает.

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

Итак, я нашел первый терминал и. Вуаля, я работал там на сервере.

Ответ 18

Вы можете использовать hot- node, чтобы предотвратить ошибки сервера/ошибки времени выполнения. Горячая node автоматически перезапускает приложение nodejs для вас всякий раз, когда происходит изменение в программе node [источник]/процесс [запуск node program].

Установите hot- node с помощью npm, используя глобальную опцию:

Ответ 19

  1. ps предоставит статус процесса, aux предоставит список: все процессы пользователя, u: процессы пользователя, x: все остальные процессы, не подключенные к терминалу.
  2. символ pipes: | передаст результат ps aux для дальнейшей манипуляции.
  3. grep будет искать предоставленную строку (в нашем случае это узел) из списка, предоставленного ps aux.

Ответ 20

При должном уважении ко всем ответам в форме я хотел бы добавить точку.

Я обнаружил, что когда я заканчиваю приложение node при ошибке с помощью Ctrl + Z, то в следующий раз, когда я пытаюсь открыть его, вы получаете ту же ошибку EADDRINUSE.

Когда я использую Ctrl + C для завершения приложения node, в следующий раз, когда я его открыл, он сделал это без сучка и задоринки.

Изменение номера порта на что-то другое, кроме ошибки, вызвало проблему.

Ответ 21

На всякий случай проверьте, добавили ли вы эту строку несколько по ошибке

Вышеприведенный код предназначен для экспресс-проверки, но просто проверьте, пытаетесь ли вы дважды использовать один и тот же порт в своем коде.

Ответ 22

Добавить функцию в

Измените изменения: source

И используйте его: killTcpListen 3000

Ответ 23

Win10, git bash v2.15, node v8.9.1, npm v5.5.1

У меня был пакет package.json script, чтобы запустить node: «start»: «node index.js»

Всякий раз, когда я использовал это, независимо от того, убил ли я его с помощью ctrl + c, я столкнулся с этой проблемой.

Если я просто запустил node index.js из git bash вместо npm run start и убил ctrl + c, я никогда не получал эту ошибку.

Я не уверен, почему, но я решил, что это может помочь кому-то.

Ответ 24

Node работает где-то в памяти и заблокирован этот порт. В Windows эта проблема, как и большинство проблем Windows, будет решена путем нажатия CTRL + ALT + DEL и/или перезагрузки.

Ответ 25

Причины этих проблем:

  • На этом порту, как Skype, может работать любое одно приложение.
  • Node может быть разбит, и порт, возможно, не был освобожден.
  • Возможно, вы попытались запустить сервер более одного. Чтобы решить эту проблему, можно поддерживать логическое значение, чтобы проверить, запущен ли сервер или нет. Его следует запускать только в том случае, если boolean возвращает false или undefined;

Ответ 26

Возможно, вы используете несколько серверов. Вы можете закрыть их и использовать один сервер. В Linux вы можете использовать команду killall node.

Ответ 27

server.close() занимает некоторое время, чтобы закрыть соединение, поэтому мы должны сделать это асинхронным вызовом как таковым:

ВАЖНО: при использовании await мы должны использовать ключевое слово async в нашей функции инкапсуляции как таковой:

Ответ 28

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

В результате таких обстоятельств я предпочитаю добавить в свой package.json :

Затем я могу позвонить им, используя:

При желании вы можете сделать это и сделать эти команды BIN с флагом аргумента. Вы также можете добавить их в качестве команд для выполнения в предложении try-catch.

Ответ 29

Будьте осторожны, что, как и я, у вас нет другого окна DOS (или подобного), которое вы забыли о x)

Он произвел точную ошибку, показанную выше!

Ответ 30

Это означает, что у вас есть два сервера node, работающих на одном и том же порту, если один из них работает на порту, скажем, 3000, изменив другой на другой порт, скажем 3001, и все будет хорошо работать

Источник

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.

Hi

First of all, thanks so much for this invaluable plugin!

I have been running Homebridge with Config UI X flawlessly since I started using Homebridge. And today out of nowhere, I can no longer access the GUI.

Safari

I’m running Homebridge in a Docker container on my Synology NAS and get this error in the logs. I definitely has something to do with port 8080 but I cannot figure out where the conflict lies.

Any help will be greatly appreciated.

Thanks in advance
Jeppe

Homebridge logs

2019-04-28 18:17:48 | stdout | �[0;37m[4/28/2019, 8:17:48 PM]�[0m �[0;36m[homebridge-config-ui-x]�[0m �[0;33mConsole v4.0.6 is listening on :: port 8080�[0m
-- | -- | --
2019-04-28 18:17:45 | stdout | (node:1318) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2019-04-28 18:17:45 | stdout | (node:1318) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
2019-04-28 18:17:45 | stdout | at process._tickCallback (internal/process/next_tick.js:63:19)
2019-04-28 18:17:45 | stdout | at doListen (net.js:1451:7)
2019-04-28 18:17:45 | stdout | at listenInCluster (net.js:1318:12)
2019-04-28 18:17:45 | stdout | at Server.setupListenHandle [as _listen2] (net.js:1270:14)
2019-04-28 18:17:45 | stdout | (node:1318) UnhandledPromiseRejectionWarning: Error: listen EADDRINUSE: address already in use :::8080

Config.json

        {
            "name": "Config",
            "port": 8080,
            "auth": "form",
            "tempUnits": "c",
            "log": {
                "method": "file",
                "path": "/var/logs/homebridge.log"
            },
            "platform": "config"
        },

Tried messing around via SSH with various commands but honestly I have very little experience with the CLI. Maybe this will reveal something.

Netstat screenshot

  • 192.168.0.99 is the Synology NAS running Homebridge
  • 192.168.0.146 is my Desktop computer
    Netstat

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.

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Hello,

Just sharing a solution to the errors below, when you run «npm start» and a port is already in use:

Error: listen EADDRINUSE 127.0.0.1:8080″ (or EADDRINUSE 127.0.0.1:3000)

1) Type «netstat -aon» on Command Prompt

2) Find the relative PID number to 127.0.0.1:8080 (or 3000)

3) Run «taskkill /f /pid pidnumber»

4) Run «npm start» again

2 Answers

Steven Parker

Sure, but before you do a brute-force kill of a running task, you may want to determine what that task is and perhaps why it was running.

tasklist /FI «PID eq pidnumber«

That command will show you the name of the running program with that pidnumber.

Simon Olsen

leo3 your solution didn’t work for me on my Mac.

I had a bit of a google around and found a snippet to add to the webpack.config.js file which will run the dev environment on a different port to 8080.

After the module: block, you need to add

devServer: {
    historyApiFallback: true,
    contentBase: "./",
    port: 3000
  }

So your full webpack.config.js file should look like this…

module.exports = {
  devtool: "inline-sourcemap",
  entry: "./index.js",
  output: {
    filename: "bundle.js"
  },
  module: {
    loaders: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        loaders: ["react-hot", "babel"]
      }
    ]
  },
  devServer: {
    historyApiFallback: true,
    contentBase: "./",
    port: 3000
  }
};

Hope this helps someone out.

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

Понравилась статья? Поделить с друзьями:
  • 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