I have a simple server running in node.js using connect:
var server = require('connect').createServer();
//actions...
server.listen(3000);
In my code I have actual handlers, but thats the basic idea. The problem I keep getting is
EADDRINUSE, Address already in use
I receive this error when running my application again after it previously crashed or errors. Since I am not opening a new instance of terminal I close out the process with ctr + z
.
I am fairly certain all I have to do is close out the server or connection. I tried calling server.close()
in process.on('exit', ...);
with no luck.
asked Nov 2, 2010 at 6:08
12
First, you would want to know which process is using port 3000
sudo lsof -i :3000
this will list all PID listening on this port, once you have the PID you can terminate it with the following:
kill -9 <PID>
where you replace <PID>
by the process ID, or the list of process IDs, the previous command output.
Teemu Leisti
3,7302 gold badges29 silver badges38 bronze badges
answered Apr 20, 2017 at 18:30
Mina GabrielMina Gabriel
21.7k26 gold badges94 silver badges122 bronze badges
15
You can also go the command line route:
ps aux | grep node
to get the process ids.
Then:
kill -9 PID
Doing the -9 on kill sends a SIGKILL (instead of a SIGTERM).
SIGTERM has been ignored by node for me sometimes.
answered Nov 22, 2010 at 16:36
djburdickdjburdick
11.6k9 gold badges44 silver badges64 bronze badges
9
I hit this on my laptop running win8. this worked.
Run cmd.exe as ‘Administrator’:
C:WindowsSystem32>taskkill /F /IM node.exe
SUCCESS: The process "node.exe" with PID 11008 has been terminated.
rsjaffe
5,5007 gold badges26 silver badges38 bronze badges
answered May 8, 2013 at 4:10
SushilSushil
5,1732 gold badges17 silver badges15 bronze badges
8
process.on('exit', ..)
isn’t called if 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…
On crash, do process.on('uncaughtException', ..)
and on kill do process.on('SIGTERM', ..)
That being said, SIGTERM (default kill signal) lets the app clean up, while SIGKILL (immediate termination) won’t let the app do anything.
answered Nov 3, 2010 at 10:22
Tor ValamoTor Valamo
32.8k11 gold badges73 silver badges81 bronze badges
1
Check the PID i.e. id of process running on port 3000 with below command :
lsof -i tcp:3000
It would output something like following:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 5805 xyz 12u IPv6 63135 0t0 TCP *:3000 (LISTEN)
Now kill the process using :
kill -9 5805
answered Nov 17, 2017 at 6:06
AyanAyan
7,8124 gold badges41 silver badges49 bronze badges
3
For macOS Monterey(12.0):
Apple introduced some changes for AirPlay on macOS Monterey. Now, it uses 5000 and 7000 ports. If you are using these ports in your project, you need to disable this feature.
System Preferences > Sharing > untick AirPlay Receiver
For macOS Ventura(13.0) and above users:
System Settings > General > disable AirPlay Receiver
answered Oct 29, 2021 at 11:46
Fatih BulutFatih Bulut
2,1151 gold badge14 silver badges10 bronze badges
0
I found this solution, try it
Give permission use sudo
sudo pkill node
answered Dec 25, 2016 at 10:21
ali ozkaraali ozkara
5,2181 gold badge26 silver badges24 bronze badges
3
I usually use
npx kill-port 3000
or on my mac.
killall node
answered Jan 24, 2022 at 2:28
Rewriting @Gerard ‘s comment in my answer:
Try
pkill nodejs
orpkill node
if on UNIX-like OS.
This will kill the process running the node server running on any port.
Worked for me.
0
Linux
Run ps
and determine the PID of your node process.
Then, run sudo kill PID
Windows
Use tasklist to display the list of running processes:
tasklist /O
Then, kill the node process like so (using the PID obtained from the tasklist
command):
taskkill /pid PID
Cody Gray♦
236k50 gold badges486 silver badges567 bronze badges
answered Nov 3, 2010 at 4:36
Shripad KrishnaShripad Krishna
10.4k4 gold badges51 silver badges65 bronze badges
3
Here is a one liner (replace 3000 with a port or a config variable):
kill $(lsof -t -i:3000)
answered Sep 15, 2018 at 6:48
floribonfloribon
19.1k4 gold badges53 silver badges66 bronze badges
1
For windows open Task Manager and find node.exe processes. Kill all of them with End Task.
answered Jan 29, 2019 at 4:03
ShahdatShahdat
5,2334 gold badges37 silver badges37 bronze badges
2
I was getting this error once and took many of the approaches here.
My issues was that I had two app.listen(3000);
calls in the same app.js script. The first app.listen() succeeded where the second threw the error.
Another useful command I came across that helped me debug was sudo fuser -k 3000/tcp
which will kill any rogue processes you might have started (some processes may restart, e.g. if run with forever.js, but it was useful for me).
answered Mar 30, 2015 at 2:46
KitKit
3,3181 gold badge26 silver badges24 bronze badges
1
For Visual Studio Noobs like me
You may be running the process in other terminals!
After closing the terminal in Visual Studio, the terminal just disappears.
I manually created a new one thinking that the previous one was destroyed. In reality, every time I was clicking on New Terminal I was actually creating a new one on top of the previous ones.
So I located the first terminal and… Voila, I was running the server there.
answered Feb 10, 2019 at 4:06
jmruedajmrueda
1,27218 silver badges28 bronze badges
0
Windows by Cmd
1/2. search => write cmd => open node.js command prompt
2/2. Run windows command: taskkill
Ends one or more tasks or processes.
taskkill /f /im node.exe
/f
— force ended
/im
— Specifies the image name of the process to be terminated.
node.exe
— executable file
Windows — Mannualy by Task Manager
This command is the same as going to Task Manager
under the details tab & select node
tasks (Tidy in my opinion).
And end task
Visual studio
Sometimes there is more than one terminal/task (client/server and so on).
Select and close by ctrl + c.
answered Mar 9, 2021 at 9:01
Ezra SitonEzra Siton
6,3292 gold badges21 silver badges34 bronze badges
1
You may run into scenarios where even killing the thread or process won’t actually terminate the app (this happens for me on Linux and Windows every once in a while). Sometimes you might already have an instance running that you didn’t close.
As a result of those kinds of circumstances, I prefer to add to my package.json
:
"scripts": {
"stop-win": "Taskkill /IM node.exe /F",
"stop-linux": "killall node"
},
I can then call them using:
npm run stop-win
npm run stop-Linux
You can get fancier and make those BIN commands with an argument flag if you want. You can also add those as commands to be executed within a try-catch clause.
answered Jun 20, 2019 at 23:36
Adam GerardAdam Gerard
6882 gold badges8 silver badges23 bronze badges
FYI, you can kill the process in one command sudo fuser -k 3000/tcp
. This can be done for all other ports like 8000, 8080 or 9000 which are commonly used for development.
Asclepius
54.5k16 gold badges157 silver badges139 bronze badges
answered May 17, 2016 at 7:34
Dat TTDat TT
2,7222 gold badges16 silver badges18 bronze badges
ps aux | grep node
kill -9 [PID] (provided by above command)
Description:
- ps will give the process status, aux provide the list of a: all users processes, u: user own processes, x: all other processes not attached to terminal.
- pipe symbol: | will pass the result of ps aux to manipulate further.
- grep will search the string provided(node in our case) from the list provided by ps aux.
answered Jul 26, 2019 at 6:50
DaniyalDaniyal
6106 silver badges10 bronze badges
1
First find out what is running using:
sudo lsof -nP -i4TCP:3000 | grep LISTEN
You will get something like:
php-fpm 110 root 6u IPv4 0x110e2ba1cc64b26d 0t0 TCP 127.0.0.1:3000 (LISTEN)
php-fpm 274 _www 0u IPv4 0x110e2ba1cc64b26d 0t0 TCP 127.0.0.1:3000 (LISTEN)
php-fpm 275 _www 0u IPv4 0x110e2ba1cc64b26d 0t0 TCP 127.0.0.1:3000 (LISTEN)
Then you can kill the process as followed:
sudo kill 110
Then you will be able to run without getting the listen EADDRINUSE :::3000 errors
answered Dec 11, 2018 at 11:42
ejntaylorejntaylor
1,8201 gold badge25 silver badges40 bronze badges
1
bash$ sudo netstat -ltnp | grep -w ':3000'
- tcp6 0 0 :::4000 :::* LISTEN 31157/node
bash$ kill 31157
tripleee
170k31 gold badges261 silver badges305 bronze badges
answered May 12, 2020 at 8:55
YanovYanov
6167 silver badges13 bronze badges
Really simply for all OS’s ..
npx kill-port 3000
Although your problem is as mentioned above you need to catch the different ways node can exit for example
process.on('uncaughtException', (err, origin) => {
console.log(err);
});
// insert other handlers.
answered Sep 22, 2022 at 11:39
Mrk FldigMrk Fldig
4,0585 gold badges33 silver badges63 bronze badges
PowerShell users:
Taskkill /IM node.exe /F
answered May 31, 2017 at 20:58
var foobarvar foobar
1591 silver badge3 bronze badges
UI solution For Windows users: I found that the top answers did not work for me, they seemed to be commands for Mac or Linux users. I found a simple solution that didn’t require any commands to remember: open Task Manager (ctrl+shift+esc). Look at background processes running. Find anything Node.js and end the task.
After I did this the issue went away for me. As stated in other answers it’s background processes that are still running because an error was previously encountered and the regular exit/clean up functions didn’t get called, so one way to kill them is to find the process in Task Manager and kill it there. If you ran the process from a terminal/powerShell you can usually use ctrl+c to kill it.
answered Mar 5, 2020 at 5:18
1
Task Manager (ctrl+alt+del) ->
Processes tab ->
select the «node.exe» process and hit «End Process»
answered Feb 17, 2016 at 13:06
Idan YehudaIdan Yehuda
5247 silver badges20 bronze badges
2
Just in case check if you have added this line multiple times by mistake
app.listen(3000, function() {
console.log('listening on 3000')
});
The above code is for express but just check if you are trying to use the same port twice in your code.
answered Jul 1, 2017 at 7:00
Arun KilluArun Killu
13.3k5 gold badges33 silver badges59 bronze badges
In windows users: open task manager
and end task
the nodejs.exe
file, It works fine.
answered Apr 3, 2020 at 2:39
NajathiNajathi
2,20123 silver badges23 bronze badges
On Windows, I was getting the following error:
EADDRINUSE: address already in use :::8081.
Followed these steps:
- Opened CMD as Admin
- Ran the folowing
command netstat -ano|findstr «PID :8081»
got the following processes:
killed it via:
taskkill /pid 43144 /f
On MAC you can do like this:
raghavkhunger@MacBook-Air ~ % lsof -i tcp:8081
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 23722 username 24u IPv6 0xeed16d7ccfdd347 0t0 TCP *:sunproxyadmin (LISTEN)
username@MacBook-Air ~ % kill -9 23722
answered Jan 19, 2021 at 6:07
RaghavRaghav
8,2766 gold badges78 silver badges104 bronze badges
With due respect to all the answers in the form, I would like to add a point.
I found that when I terminate a node app on error using Ctrl + Z, the very next time when I try to open it got the same error EADDRINUSE.
When I use Ctrl + C to terminate a node app, the next time I opened it, it did without a hitch.
Changing the port number to something other than the one in error solved the issue.
answered Mar 15, 2017 at 14:12
2
using netstat to get all node processes with the port they are using and then kill the only one you want by PID
netstat -lntp | grep node
you will get all node processes
tcp6 0 0 :::5744 :::* LISTEN 3864/node
and then when you get the PID (3864) just kill the processes by PID
kill -HUP PID
answered Jul 3, 2021 at 7:10
You may use hot-node to prevent your server from crashing/ run-time-errors. Hot-node automatically restarts the nodejs application for you whenever there is a change in the node program[source] / process[running node program].
Install hot-node using npm using the global option:
npm install -g hotnode
answered Sep 14, 2013 at 9:16
touchStonetouchStone
3181 silver badge16 bronze badges
2
Содержание
- 15 Common Error Codes in Node.js and How to Fix Them
- 🔭 Want to centralize and monitor your Node.js error logs?
- 1. ECONNRESET
- 2. ENOTFOUND
- Check the domain name
- Check the host value
- Check your localhost mapping
- 3. ETIMEDOUT
- 4. ECONNREFUSED
- 5. ERRADDRINUSE
- 6. EADDRNOTAVAIL
- 7. ECONNABORTED
- 8. EHOSTUNREACH
- 9. EAI_AGAIN
- 10. ENOENT
- 11. EISDIR
- 12. ENOTDIR
- 13. EACCES
- 14. EEXIST
- 15. EPERM
- Fixing nodemon ‘Error: listen EADDRINUSE: address in use’
- Has this ever happened to you?
- Luckily there is a solution!
- Save this command for future use
- The quick and easy way to save
- The slightly more advanced way to save
- How to kill server when seeing “EADDRINUSE: address already in use”
- The Problem
- The cause behind this issue
- Solution
- Kill the process manually
- For Mac/Linux
- For Windows
- Enjoy!
- Level Up Coding
15 Common Error Codes in Node.js and How to Fix Them
Contents
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.
lightbox#close» data-lightbox-target=»img» src=»https://imagedelivery.net/xZXo0QFi-1_4Zimer-T0XQ/ac93c9ef-a7f6-4cff-0bcd-14982ccc7f00/orig»/>
🔭 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:
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:
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:
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).
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:
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.
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.
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:
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:
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:
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:
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:
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:
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.
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.
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.
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.
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.
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):
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
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:
The solution here is to check if the path exists through fs.existsSync() before attempting to create it:
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:
- Close all instances of your editor before rerunning the command (maybe some files were locked by the editor).
- Clean the npm cache with npm cache clean —force .
- Close or disable your Anti-virus software if have one.
- If you have a development server running, stop it before executing the installation command once again.
- Use the —force option as in npm install —force .
- Remove your node_modules folder with rm -rf node_modules and install them once again with npm install .
Источник
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.
Источник
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.
Источник
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:
- Close all instances of your editor before rerunning the command (maybe some
files were locked by the editor). - Clean the
npm
cache withnpm cache clean --force
. - Close or disable your Anti-virus software if have one.
- If you have a development server running, stop it before executing the
installation command once again. - Use the
--force
option as innpm install --force
. - Remove your
node_modules
folder withrm -rf node_modules
and install them
once again withnpm 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
Next article
How to Configure Nginx as a Reverse Proxy for Node.js Applications
→
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
Hey! When I did create-dazzle-app
and then yarn start
I got the following error:
yarn run v1.3.2
$ razzle start
WAIT Compiling...
events.js:137
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::3001
at Object._errnoException (util.js:1003:13)
at _exceptionWithHostPort (util.js:1024:20)
at Server.setupListenHandle [as _listen2] (net.js:1366:14)
at listenInCluster (net.js:1407:12)
at Server.listen (net.js:1495:7)
at Server.listen (/node_modules/webpack-dev-server/lib/Server.js:479:47)
at Object.<anonymous> (/node_modules/razzle/scripts/start.js:80:17)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:617:3
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I had another app running at port 3001 so I guess the fault lies with me, but the error handling could be better. Here’s the relevant code:
// Create a new instance of Webpack-dev-server for our client assets. | |
// This will actually run on a different port than the users app. | |
const clientDevServer = new devServer(clientCompiler, clientConfig.devServer); | |
// Start Webpack-dev-server | |
clientDevServer.listen( | |
(process.env.PORT && parseInt(process.env.PORT) + 1) || razzle.port || 3001, | |
err => { | |
if (err) { | |
logger.error(err); | |
} | |
} | |
); | |
} |
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
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.
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.