Closed tiagosalema closed 3 years ago
basic MERN app
Can you explain and provide example code? Because I'm pretty sure "basic" actually means: set up mongodb, add nginx, possibly webpack and a bunch others. i.e. not compatible with "basic".
If you can provide code that replicates this issue, happy to look at it. Otherwise this is too vague.
This is the repo where I am running it.
server.js roughly looks like this:
const app = express();
connectDB(); // mongoose
// Routes...
// serve static assets in production (React app)
if (['production', 'ci'].includes(process.env.NODE_ENV)) {
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, '..', 'client', 'build', 'index.html'));
});
}
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server started on port ${PORT}`));
Okay, start striping the code back until you have the bare minimum and you can still replicate, then post that here, then we can take a look.
I've recently started facing the same issue on my own application. Nodemon was working fine all this while but now seems to be leaving a single Node process listening on an open port (3000, in my case). I looked up past issues on the GitHub repo and found that the most popular one had been closed last year.
My stripped-down entry file (app.js) looks like this:
const express = require('express');
const app = express();
app.listen(3000, () => console.log('listening on port 3000...'));
app.get('/', (req, res) => res.send('Home'));
As for other environment and version info:
Right now, I'm forced to manually kill the running process myself and restart the Node server, which defeats the purpose of using Nodemon at all. Any help is appreciated.
I've found a temporary work-around, the steps for which are listed below:
npm install -D kill-port
{
"events": {
"restart": "kill-port 3000",
"crash": "kill-port 3000"
},
"delay": "1500"
}
"scripts": {
"dev": "nodemon app.js",
},
All credit goes to Tudor Constantin on Stack Overflow. However, it is a bit tedious and definitely a workaround, not something that should be done for all future Node.js projects.
Correction: The method I've shown above provides inconsistent results, and shouldn't be considered a fix. It only works half of the time, and also occasionally crashes when Nodemon restarts.
Back to the drawing board...
I came across variants of this issue many times without ever being able to replicate it deterministically. But on all cases, I have found that...
${port}
on the nodemon
events start
, restart
or crash
, does not solve my problem..listen(...)
on my express
app does not solve my problem..listen(...)
in a .then()
does solve my problem, when...
fuser -k ${port}/tcp
and npx kill-port ${port}
is used to kill the port-process.nodemon
restart is delayed (hint: to delay it, merge your current nodemon.json
with {delay: ${milliseconds}}
). I have the solution below running almost all of the times with {delay: "500"}
.I have written a brief code snippet that does the job of killing the conflicting port-process at run-time, using fuser
. I don't think adapting the code so as to use npx kill-port ${port}
would be very hard: I would appreciate if anyone could augment my code with that adaptation :)
Basically, one call of killPort
keeps killing all the port-processes that hold onto the port ${port}
until no processes are left. Finally, an interval is set so that if a round of killPort
has killed any process, it checks again after some time. This killing and re-killing was done because for some reason the conflicting port-processes would get killed once but the error EADDRINUSE
would still show up. It may be overkill, pun intended, but to be honest, it works, and I'm happy because of that.
Here it is, along with my current use case and its output:
import {execSync} from 'child_process';
const buildKillPortPromise = (port: number) => new Promise(
(resolve) => {
const killPort = () => {
let hasKilled = false;
while (true) {
const pid = execSync(
`fuser -k ${port}/tcp || echo '---'`, // fuser exits with 1 when no process has been killed
{stdio: ['ignore', 'pipe', 'ignore']}, // https://nodejs.org/api/child_process.html#child_process_options_stdio
).toString().trim();
if (pid !== '---') {
hasKilled = true;
console.log(`PID ${pid} was holding onto port ${port}. It was killed.`);
} else {
return hasKilled;
}
};
};
const intervalId = setInterval(() => {
if (!killPort()) {
clearInterval(intervalId);
resolve(undefined);
}
}, 500); // this is the minimum that I have found that works consistently
},
);
@tiagosalema , I was having same problem and i restarted my system and its fixed now. Wow, that was easy to fix :rofl:
@tiagosalema , I was having same problem and i restarted my system and its fixed now. Wow, that was easy to fix 🤣
Lmao the same thing happened to me, I just didn't write about it because I didn't think it was replicable. The old "Have you tried turning it off and on again?" worked for me too. 😂
@tiagosalema , I was having same problem and i restarted my system and its fixed now. Wow, that was easy to fix 🤣
Your system as in computer? I've tried a few different things to no avail, including
@tiagosalema , I was having same problem and i restarted my system and its fixed now. Wow, that was easy to fix rofl
Your system as in computer? I've tried a few different things to no avail, including
* restarting the project * restarting the computer * deleting and reinstalling all node_modules * assigning the port as an environment variable instead of assigning it in the app (a stackoverflow answer suggested that)
What os are you using, i am using popos latest that is based on ubuntu 20.04 lts.
i already have this issue. im using express mongodb joi
nodemon
it happened two times first time i try delete and re install all node modules and it not work. i try restating my PC several times and its not working then i totally uninstall nodejs and re install it. That time it works correctly
after few days now (2021/5/9 10:29PM ) its show this error again :-(
i already have this issue. im using express mongodb joi
nodemon
it happened two times first time i try delete and re install all node modules and it not work. i try restating my PC several times and its not working then i totally uninstall nodejs and re install it. That time it works correctly
after few days now (2021/5/9 10:29PM ) its show this error again :-(
Try this..
npm cache clean --force
, and see if nodemon works after that ..?
i get port in use also and i am running on linux, is there any way to make nodemon wait for the process to close before it tries to run a new one?
process.on("SIGUSR2", () => {
console.log("server shutting down");
setTimeout(() => {
console.log("hello?");
}, 5000);
});
[nodemon] restarting due to changes...
Server shutting down
[nodemon] starting `node ./bin/www`
Port 3020 is already in use
[nodemon] app crashed - waiting for file changes before starting...
hello?
see the hello? message showing up from first process while nodemon already tried running the process again before it.
shouldn't this cause nodemon to have to wait? as the process is still running? also in the example of nodemon trying to use once instead of on doesn't work since nodemon sends the SIGUSR2 twice and the second one just causes the code not to finish running at all.
i don't know if this helps or i am doing something wrong. i was thinking to do server.close() and delay the process.exit but it seems like nodemon just opens another process before this one closes.
This issue is being a little hijacked!
I can tell folks that the example supplied still isn't parred down enough - this version (because it's actually running on a different system which and is due to an entirely different problem). I get that it's hard to pare down - but it has to happen to be able to first replicate which allows way for a fix.
For those on windows the issue you were facing has been fixed in 2.0.9.
I'm going to close this issue because the follow on posts have the same vague symptom but don't answer those prerequisite questions specifically about OS.
In addition, the original OP, @tiagosalema hasn't been able to recreate using the example repo and jumping through the whole setup:
node @ v14.15.1 nodemon @ 2.0.9 (a couple of bump, but specific to windows)
In case you're in windows try to 'End task' for all node.js processes (What worked for me), if you are on Linux then use this command: _kill $(lsof -t -i:PORT) Replace PORT with the one you have your server running in.
In case anyone is still facing this issue even after killing the PID, just restart your machine. Seemed to fix it for me. Weird fix, I'm sure the issue is on nodemon's side.
hi, I am quite new in nodejs and express, getting this error and not finding any solution. Please help me. thanks!
C:\D\PlayBox\back_end\middlewares\auth.js:41
return res.sendStatus(401).send("Invalid Token");
^
TypeError: Cannot read properties of undefined (reading 'sendStatus')
at Object.verifyToken (C:\D\PlayBox\back_end\middlewares\auth.js:41:16)
at C:\D\PlayBox\back_end\app.js:70:21
at Layer.handle [as handle_request] (C:\D\PlayBox\back_end\node_modules\express\lib\router\layer.js:95:5)
at next (C:\D\PlayBox\back_end\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\D\PlayBox\back_end\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\D\PlayBox\back_end\node_modules\express\lib\router\layer.js:95:5)
at C:\D\PlayBox\back_end\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\D\PlayBox\back_end\node_modules\express\lib\router\index.js:341:12)
at next (C:\D\PlayBox\back_end\node_modules\express\lib\router\index.js:275:10)
at jsonParser (C:\D\PlayBox\back_end\node_modules\body-parser\lib\types\json.js:119:7)
[nodemon] app crashed - waiting for file changes before starting...
function verifyToken(req, res, next) {
let token = req.body.token || req.query.token || req.headers["authorization"];
token = token.split(" ")[1];
console.log(">>>>>token " + token);
if (!token) {
return res.send(403, "A token is required for authentication");
}
try {
const decoded = jwt.verify(token, "process.env.ACCESS_TOKEN_SECRET");
req.user = decoded;
} catch (err) {
return res.sendStatus(401).send("Invalid Token");
}
return next();
}
getting error in this line >>> return res.sendStatus(401).send("Invalid Token");
reinicia la pc bro
I've recently started facing the same issue on my own application. Nodemon was working fine all this while but now seems to be leaving a single Node process listening on an open port (3000, in my case). I looked up past issues on the GitHub repo and found that the most popular one had been closed last year.
My stripped-down entry file (app.js) looks like this:
const express = require('express'); const app = express(); app.listen(3000, () => console.log('listening on port 3000...')); app.get('/', (req, res) => res.send('Home'));
As for other environment and version info:
- Node.js: v15.14.0
- Nodemon: 2.0.7
- Express: 4.17.1
- OS: Ubuntu 20.04.2 LTS on Windows 10 (WSL 2)
Right now, I'm forced to manually kill the running process myself and restart the Node server, which defeats the purpose of using Nodemon at all. Any help is appreciated.
Facing same issue. If we have to restart everything by killing previous session then what is use of nodemon
Error: listen EADDRINUSE: address already in use :::5000
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 5000
}
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting node server.js
AI server started on http://localhost:3000
if you use MacOS turn off “AirPlay Receiver” in the “Sharing” System Preference
I've recently started facing the same issue on my own application. Nodemon was working fine all this while but now seems to be leaving a single Node process listening on an open port (3000, in my case). I looked up past issues on the GitHub repo and found that the most popular one had been closed last year. My stripped-down entry file (app.js) looks like this:
const express = require('express'); const app = express(); app.listen(3000, () => console.log('listening on port 3000...')); app.get('/', (req, res) => res.send('Home'));
As for other environment and version info:
- Node.js: v15.14.0
- Nodemon: 2.0.7
- Express: 4.17.1
- OS: Ubuntu 20.04.2 LTS on Windows 10 (WSL 2)
Right now, I'm forced to manually kill the running process myself and restart the Node server, which defeats the purpose of using Nodemon at all. Any help is appreciated.
Facing same issue. If we have to restart everything by killing previous session then what is use of nodemon
if you use MacOS turn off “AirPlay Receiver” in the “Sharing” System Preference
Yep. Confirming this is an AirPlay issue if you use MacOS. It's using port 5000 by default.
Open a new terminal tab and enter: lsof -i tcp:5000
and you might see ControlCe.
Turning off AirPlay receiver is just one click in the settings, didn't need to restart or anything.
Kind of a weird error lol
if you use MacOS turn off “AirPlay Receiver” in the “Sharing” System Preference
This is the one! Saving me from a ton of headaches!
my problem was solved by using an explicit host on mac os
app.listen(+port,'localhost', () => {
console.log(`app start http://localhost:${port}`)
})
and off “AirPlay Receiver” in the “Sharing” System Preference
i already have this issue. im using express mongodb joi nodemon it happened two times first time i try delete and re install all node modules and it not work. i try restating my PC several times and its not working then i totally uninstall nodejs and re install it. That time it works correctly after few days now (2021/5/9 10:29PM ) its show this error again :-(
Try this..
npm cache clean --force
, and see if nodemon works after that ..?
Clearing the cache worked wonders for me- thanks so much!
nodemon -v
: 2.0.7node -v
: 14.16.01Expected behaviour
Close port before reinitializing server.
Actual behaviour
Steps to reproduce
This only started happening after I updated my Mac to Big Sur. I can circumvent this issue by either stopping the app and killing the port or by saving a second time a couple of seconds after the first crashed the server.