Despite app.listen, express app does not bind to port - node.js

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.

Related

ExpressJS Node Process won't end "normally"

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

my discord bot works well for a while but then "failed to bind to $PORT within 60 seconds of launch"

I've tried different approaches and looked at all the other replies but i dont know how to adress it
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2022-03-19T09:15:18.022903+00:00 heroku[web.1]: Stopping process with SIGKILL
2022-03-19T09:15:18.059850+00:00 app[web.1]: Error waiting for process to terminate: No child processes
2022-03-19T09:15:18.210022+00:00 heroku[web.1]: Process exited with status 22
2022-03-19T09:15:18.331083+00:00 heroku[web.1]: State changed from starting to crashed
the code:
require('dotenv').config();
const OpenAI = require('openai-api');
const openai = new OpenAI(process.env.OPENAI_API_KEY);
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
let prompt =`text here`;
client.on("message", function (message) {
if (message.author.bot) return;
prompt += `You: ${message.content}\n`;
(async () => {
const gptResponse = await openai.complete({
engine: 'davinci',
prompt: prompt,
maxTokens: 80,
temperature: 0.7,
topP: 1,
presencePenalty: 0,
frequencyPenalty: 0,
bestOf: 1,
n: 1,
stream: false,
stop: ['\n', '\n\n']
});
message.reply(`${gptResponse.data.choices[0].text.substring(5)}`);
prompt += `${gptResponse.data.choices[0].text}\n`;
})();
});
client.login(process.env.BOT_TOKEN);
my procfile is empty but it still works for 60 seconds
any ideas?
edit: THINGS I TRIED THAT DONT WORK
i tried changing procfile to contain
worker: node index.js
procfile to worker: java -jar build/libs/*.jar
Use the name Procfile instead of procfile, otherwise heroku doesn't learns that you need worker process and not the default web process.

Error when running firebase node app on Heroku

The code (server.js) is as following following the Firebase documentation example
var firebase = require("firebase");
firebase.initializeApp({
databaseURL: "https://mydatabaseName.firebaseio.com",
});
var db = firebase.database();
var ref = db.ref("/Users");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
});
but I'm running into the error
Error waiting for process to terminate: No child processes
State changed from starting to crashed
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
Stopping process with SIGKILL
Process exited with status 22
After googling this issue, I tried adding to the Procfile
worker: node server.js
heroku ps:scale worker=1 web=0
None of these seemed to work. Any suggestions?

mocha watching fails under npm

I have a very simple Koa application:
var app = module.exports = require("koa")();
app.use(function *(){
this.body = "Koa says Hi!";
});
var port = process.env.PORT || (process.argv[2] || 3000);
port = (typeof port === "number") ? port : 3000;
app.listen(port);
console.log("Application started. Listening on port:" + port);
that I test with mocha and supertest like this;
var app = require("../");
var request = require("supertest").agent(app.listen());
describe("Our amazing site", function () {
it("has a nice welcoming message", function (done) {
request
.get("/")
.expect("Koa says Hi!")
.end(done);
});
});
I want to watch my files for changes and use the -w flag like this
mocha -u bdd -R min -w
That works fine. I change a file, the test is reexcuted and all is well.
But, very strangely, if I move that command into my package.json file as a script, like this:
"scripts": {
"watch:test": "mocha -u bdd -R min -w"
},
The first time I run the command it works, when I make a change that is picked up but now the test fails with:
1) Uncaught error outside test suite:
Uncaught Error: listen EADDRINUSE :::3000
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at Server._listen2 (net.js:1231:14)
at listen (net.js:1267:10)
at Server.listen (net.js:1363:5)
at Application.app.listen (node_modules/koa/lib/application.js:70:24)
at Object.<anonymous> (index.js:10:5)
at Object.<anonymous> (test/site.spec.js:1:73)
at Array.forEach (native)
at StatWatcher._handle.onchange (fs.js:1285:10)
That error will not go away until I stop mocha and then restart it.
Why does it behave differently when run via npm?
What can I do to fix this?
Ok - I found the solution. This has to do with that I'm starting an app twice, when under test. And not closing both.
To start testing with Supertest you construct a request like this: var request = require("supertest").agent(app.listen());. Btw the app.listen() is the same thing as we do in our application.
Since we are watching our files for changes the server never gets close. On the next run of the test it starts again: var request = require("supertest").agent(app.listen()); and the "Address is in use".
The solution is simple: just start listening when you are not running under test. A simple way to do that is by checking for a module parent in your application:
if(!module.parent) {
app.listen();
}

Openshift + Meteor = listen EACCES?

I deployed Meteor.js on a Node 0.6 + Mongo 2.2 Openshift cartridge with a custom Node 0.8.24 installed in the data dir (sort of like this tutorial).
I do set the right ports before calling the app. My code in server.js looks like that:
// Setup env
process.env.ROOT_URL = "http://" + (process.env.OPENSHIFT_APP_DNS || "localhost");
process.env.MONGO_URL = (process.env.OPENSHIFT_MONGODB_DB_URL + process.env.OPENSHIFT_APP_NAME) || "mongodb://localhost:27017/";
process.env.PORT = process.env.OPENSHIFT_NODEJS_PORT || 8000;
process.env.IP = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0';
// Show connection details on startup
console.log("MONGO_URL IS: " + process.env.MONGO_URL);
console.log("ROOT_URL IS: " + process.env.ROOT_URL);
console.log("PORT: " + process.env.PORT);
console.log("IP: " + process.env.IP);
require(require('path').join(__dirname, 'main.js'));
Then, when I rhc app restart myappname the app, I get:
> node server.js
MONGO_URL IS: mongodb://<login>:<pass>#127.5.x.x:27017/<myapp>
ROOT_URL IS: http://<myappname>-<mydomain>.rhcloud.com
PORT: 8080
IP: 127.5.x.x
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EACCES
at errnoException (net.js:770:11)
at Server._listen2 (net.js:893:19)
at listen (net.js:932:10)
at Server.listen (net.js:1006:9)
at dns.js:72:18
at process.startup.processNextTick.process._tickCallback (node.js:245:9)
npm info <mydomain>#0.0.1 Failed to exec start script
npm ERR! weird error 1
npm ERR! not ok code 0
main.js is he regular entry point for my Meteor app.
The env settings look like the right ones. Why do I keep getting this EACCESS?

Resources