ExpressJS Node Process won't end "normally" - node.js

NodeJS v 16.15.1 Windows 10.
Since a few days, neither nodemon nor VSCode can end node processes which use app.listen() of express. When the code changes we see:
[nodemon] restarting due to changes...
But nothing happens after that. We have to kill the processes manually in task manager.
'use strict';
const express = require('express');
const app = express();
const PORT = 8040;
// The PROBLEMATIC line:
app.listen(PORT, () => {
console.log(`Started on http://localhost:${PORT} (PID: ${process.pid})`);
});
If I remove "The PROBLEMATIC line" then nodemon/vscode can restart the process.
There is NO error message, the app just does not exit. For example by entering rs:
Nothing happens, no matter how long I wait.
Using nodemon --signal SIGTERM makes no difference, the process never sees the SIGTERM.
Using the package why-is-node-running we see:
There are 5 handle(s) keeping the process running
# TCPSERVERWRAP
C:\services\overview\node_modules\express\lib\application.js:635 - return server.listen.apply(server, arguments);
C:\services\overview\src\tmp2.js:6 - app.listen(PORT, () => {
# TTYWRAP
C:\services\overview\src\tmp2.js:7 - console.log(`Started on http://localhost:${PORT} (PID: ${process.pid})`);
# HTTPINCOMINGMESSAGE
(unknown stack trace)
# HTTPINCOMINGMESSAGE
(unknown stack trace)
# TickObject
(unknown stack trace)

You want end the node/nodemon process? Why not using ctrl + c instead

Related

It won't accept command line after first run

I ran my first server and seems fine except that it won't stop running. I cannot even type anything else in the command line. I will appreciate any help
Here is the code I ran
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) =>
{
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('In the name of Allah, the Most Gracious, the Most Merciful.');
});
server.listen(port, hostname, () =>
{
console.log(`Server running at http://${hostname}:${port}/`);
});
But the problem is not the code, rather how to get back to this command line
$papus#QuantumOne MINGW64 /c/Projects/firstServer so that I can start retyping again on the command line without closing everything down and restart the whole process.
right now it gets stuck on Server running at http://127.0.0.1:3000 forever
Because it is a server and it is not supposed to stop after a time.
You can shut down by pressing ctrl + c
Or you can program a certain route that will kill it programatically (i did not say it should be done)
If you want to continue using the same terminal you can run the server in background (on unix systems it is done by adding & at the end of the start command)
You can also look at process manager for nodejs server like pm2

Despite app.listen, express app does not bind to port

Exactly what it sounds like.
I use ExpressJS for my Node app, which is hosted on Heroku.
Despite using app.listen, it consistently is getting / causing heroku R10 errors, which are caused by a web app not binding to process.env.PORT in time.
The relevant code:
const app = express();
var isRoot = (process.getuid && (process.getuid() === 0));
var port;
if (isRoot) {
port = 80;
} else {
port = process.env.PORT | 8000;
}
const server = app.listen(port, onStartup);
function onStartup() {
console.log("Started webserver on port "+port);
}
Now the odd thing is, I'm getting the "Started webserver on port [foo]" message, it's just not binding to the port.
Logs:
2020-03-30T19:50:39.434302+00:00 app[web.1]: > foo-bar#1.0.0 start /app
2020-03-30T19:50:39.434303+00:00 app[web.1]: > node scrape2.js
2020-03-30T19:50:39.434303+00:00 app[web.1]:
2020-03-30T19:50:39.829882+00:00 app[web.1]: Verbose mode OFF
2020-03-30T19:50:39.830782+00:00 app[web.1]: Started webserver on port 8052
2020-03-30T19:51:37.415192+00:00 heroku[web.1]: State changed from starting to crashed
2020-03-30T19:51:37.293060+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2020-03-30T19:51:37.293142+00:00 heroku[web.1]: Stopping process with SIGKILL
2020-03-30T19:51:37.391762+00:00 heroku[web.1]: Process exited with status 137
Help!
I did a stupid and accidentally used the bitwise OR operator, which caused it to bind to a different port than process.env.PORT. Changed it from | to || and it works fine now.

My express server is not exiting with both ctrl + c and process.exit(1)

I am getting an error message:
listen EADDRINUSE: address already in use :::3000.
When I tried after removing the server starting code(i.e app.listen part) nothing is happening
const path = require('path')
const express = require('express')
//var publicPathDirectory = path.join(__dirname,"../public")
const app = express()
app.listen(3000,()=>{
console.log('server started')
})
process.on('SIGINT', function() {
console.log( "\nGracefully shutting down from SIGINT (Ctrl-C)" );
// some other closing procedures go here
process.exit(1);
});
I've had this happen to me before, where even though I quit the node server with CTRL+C, it still is hogging port 3000. You can kill node with:
pkill -f node
Potentially related to Node.js Port 3000 already in use but it actually isn't?
Use number 1 inside exit only when you have an exit with failure. To force exit do not use number inside exit().
process.exit()
Please take a look at here. May be you can understand. link

Forked child process keeps terminated with code 1

I wrapped a module using Electron Packager. Because it has heavy computation, i put it in a sub process that would be forked from renderer.js when user clicks a button on index.html.
Pseudo-code renderer.js from :
let cp = require('child_process');
let subprocess;
function log(msg) {
// A function to log messages sent from subprocess
}
document.querySelector('#create').addEventListener('click', ev => {
subprocess = cp.fork('./subprocess.js');
log('A subprocess has been created with pid: ' + subprocess.pid + ' with exexPath = ' + process.execPath);
subprocess.on('exit', (code, signal) => log(`child process terminated: signal = ${signal} ; code = ${code}`));
subprocess.on('error', log);
subprocess.on('message', log);
});
The real problem is: this subprocess runs smoothly when i call electron ./ from console in working directory, but the build generated by Electron Packager wouldn't.
The subprocess does not show up in Task Manager, or rather, it is terminated as soon as it appears. The log says child process terminated: signal = null ; code = 1.
Although i guarded at the beginning of subprocess.js with this to catch uncaughtException
process.on('uncaughtException', (err) => {
process.send(`Caught exception: ${err}`);
});
Nothing is recorded in log. What should i do to overcome this situation?
System specs:
Window 10
Node 8.6
Electron 1.7.12
Electron Packager 10.1.2
I have experienced this too. One reason i came up with was because the child process will be the child process of electron itself.
In my case, it will not recognize the node modules i defined.
I suggest using spawn with the spawn process being node.exe. But that will not be practical once you build your app.

How to debug Node.JS child forked process?

I'm trying to debug the child Node.JS process created using:
var child = require('child_process');
child .fork(__dirname + '/task.js');
The problem is that when running in IntelliJ/WebStorm both parent and child process start on the same port.
debugger listening on port 40893
debugger listening on port 40893
So it only debugs the parent process.
Is there any way to set IntelliJ to debug the child process or force it to start on a different port so I can connect it in Remote debug?
Yes. You have to spawn your process in a new port. There is a workaround to debug with clusters, in the same way you can do:
Start your app with the --debug command and then:
var child = require('child_process');
var debug = typeof v8debug === 'object';
if (debug) {
//Set an unused port number.
process.execArgv.push('--debug=' + (40894));
}
child.fork(__dirname + '/task.js');
debugger listening on port 40894
It is a known bug in node.js that has been recently fixed (although not backported to v0.10).
See this issue for more details: https://github.com/joyent/node/issues/5318
There is a workaround where you alter the command-line for each worker process, although the API was not meant to be used this way (the workaround might stop working in the future). Here is the source code from the github issue:
var cluster = require('cluster');
var http = require('http');
if (cluster.isMaster) {
var debug = process.execArgv.indexOf('--debug') !== -1;
cluster.setupMaster({
execArgv: process.execArgv.filter(function(s) { return s !== '--debug' })
});
for (var i = 0; i < 2; ++i) {
if (debug) cluster.settings.execArgv.push('--debug=' + (5859 + i));
cluster.fork();
if (debug) cluster.settings.execArgv.pop();
}
}
else {
var server = http.createServer(function(req, res) {
res.end('OK');
});
server.listen(8000);
}
Quick simple fix ( where using chrome://inspect/#devices )
var child = require('child_process');
child.fork(__dirname + '/task.js',[],{execArgv:['--inspect-brk']});
Then run your app without any --inspect-brk and the main process won't debug but the forked process will and no conflicts.
To stop a fork conflicting when debugging the main process ;
child.fork(__dirname + '/task.js',[],{execArgv:['--inspect=xxxx']});
where xxxx is some port not being used for debugging the main process. Though I haven't managed to easily connect to both at the same time in the debugger even though it reports as listening.
I find that setting the 'execArgv' attribute in the fork func will work:
const child = fork('start.js', [], {
cwd: startPath,
silent: true,
execArgv: ['--inspect=10245'] });
if "process.execArgv" doenst work you have to try:
if (debug) {
process.argv.push('--debug=' + (40894));
}
this worked for me..
There are one more modern way to debug child (or any) process with Chrome DevTools.
Start your app with arg
--inspect
like below:
node --debug=9200 --inspect app/main.js
You will see the message with URL for each child process:
Debugger listening on port 9200.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9200/207f2ab6-5700-4fc5-b6d3-c49a4b34a311
Debugger listening on port 9201.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9201/97be3351-2ea1-4541-b744-e720188bacfa
Debugger listening on port 9202.
Warning: This is an experimental feature and could change at any time.
To start debugging, open the following URL in Chrome:
chrome-devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9202/8eb8384a-7167-40e9-911a-5a8b902bb8c9
If you want to debug the remote processes, just change the address 127.0.0.1 to your own.

Resources