What is the use of setting a port in gulp-nodemon? - node.js

I am using gulp-nodemon because of its most obvious of utilities.
Nodemon is a utility that will monitor for any changes
in your source and automatically restart your server.
But I am not understanding a practice which seems to be prevalent in express/node development.
I just started working with node and express but from what I understand:
app.js
var express = require('express'),
app = express(),
port = process.env.PORT || 8016;
app.get('/', function rootHndlr(req, res) {
/* body... */
res.send('welcome to my API!');
});
app.listen(port, function listenHndlr(){
console.log('Gulp is running my app on PORT ' + port);
});
The following is setting in the port to 8016 if not set.
port = process.env.PORT || 8016;
So now we binds and listens for connections on the specified host and port.
But then I see people configure in their gulp tasks the following to nodemon in their gulpfile.js
gulpfile.js
var gulp = require('gulp'),
nodemon = require('gulp-nodemon');
gulp.task('default', function() {
// content
nodemon({
script: 'app.js',
ext: 'js'
env: {
PORT: 8000
},
ignore: ['./node_modules/**']
}).
on('restart', function(){
consile.log('Restarting');
});
});
As you can one of the values in nodemon env: {PORT: 8000} Why set the port again?
Thanks!

People are using something like that as a fallback: port = process.env.PORT || 8016;
Your application should be flexible enough and by passing an env var to make it listen to another port. In general, this is the purpose of the env vars.
About your example, I suppose that there is a reason that the guy that wrote this gulpfile would like to make the app listen to port 8000. I would say that it is safe to change the value or to remove the PORT: 8000 as soon as you are 100% sure that there is no reason that the application needs to run on port 8000 (for example, it is behind a reverse proxy that forwards the traffic to port 8000).

Related

after deploying in heroku an error was popped up [duplicate]

I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn't let me write so much code, so I would just say that the running the code locally as well within my network shows no issue.
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting for ');
console.log(request);
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
console.log(filePath);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(5000);
console.log('Server running at http://127.0.0.1:5000/');
Any idea ?
Heroku dynamically assigns your app a port, so you can't set the port to a fixed number. Heroku adds the port to the env, so you can pull it from there. Switch your listen to this:
.listen(process.env.PORT || 5000)
That way it'll still listen to port 5000 when you test locally, but it will also work on Heroku. Important note - PORT word must be capital.
You can check out the Heroku docs on Node.js here.
It's worth mentioning that if your code doesn't specify a port, then it shouldn't be a web process and probably should be a worker process instead.
So, change your Procfile to read (with your specific command filled in):
worker: YOUR_COMMAND
and then also run on CLI:
heroku scale worker=1
For those that are passing both a port and a host, keep in mind that Heroku will not bind to localhost.
You must pass 0.0.0.0 for host.
Even if you're using the correct port. We had to make this adjustment:
# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;
# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;
Then you can start the server, as usual:
app.listen(port, host, function() {
console.log("Server started.......");
});
You can see more details here: https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error
The error happens when Heroku failed to bind the port or hostname at server.listen(port, [host], [backlog], [callback]).
What Heroku requires is .listen(process.env.PORT) or .listen(process.env.PORT, '0.0.0.0')
So more generically, to support other environments, use this:
var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
console.log('Listening on port %d', server_port);
});
I had same issue while using yeoman's angular-fullstack generated project and removing the IP parameter worked for me.
I replaced this code
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
with
server.listen(config.port, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
In my case, I was using example from https://hapijs.com/
To fix the problem I replaced
server.connection({
host: 'localhost',
port: 8000
});
with
server.connection({
port: process.env.PORT || 3000
});
change this line
app.listen(port);
to
app.listen(process.env.PORT, '0.0.0.0');
it will work
While most of the answers here are valid, for me the issue was that I was running long processes as part of npm run start which caused the timeout.
I found the solution here and to summarize it, I just had to move npm run build to a postinstall task.
In other words, I changed this:
"start": "npm run build && node server.js"
to this:
"postinstall": "npm run build",
"start": "node server.js"
Come to think of this, it totally makes sense because this error (which used to appear occasionally) was becoming more and more common as my app kept growing.
Changing my listening port from 3000 to (process.env.PORT || 5000) solved the problem.
Restarting all dynos in heroku did the trick for me
In my case, I was using Babel with the babel-plugin-transform-inline-environment-variables plugin. Apparently, Heroku does not set the PORT env variable when doing a deployment, so process.env.PORT will be replaced by undefined, and your code will fallback to the development port which Heroku does not know anything about.
I realized that I don't need the port number in the request endpoint, so the endpoint was herokuapp.com and not herokuapp.com:5000.
The listen() call can be without host and callback:
server.listen(5000);
I Use ReactJs,
If you want upload to heroku add this in your webpack.config.js
Because if not add you will have error
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within
60 seconds of launch
//webpack.config.js add code like that
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
var server_port = process.env.YOUR_PORT || process.env.PORT || 5000;
var server_host = process.env.YOUR_HOST || "0.0.0.0";
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
devServer: {
disableHostCheck: true,
contentBase: "./ dist",
compress: true,
inline: true,
port: server_port,
host: server_host
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
I had the same issue because I didn't define Procfile. Commit a text file to your app's root directory that is named Procfile without a file extension. This file tells Heroku which command(s) to run to start your app.
web: node app.js
Edit package.json:
...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...
and Server.js:
...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...
I've spent a lot of hours to find the root cause, and eventually I've found that this timeout (60s) can be adjustable. Here you may change 60 second to 120 or even more. It works for me, hope will help anybody else!
To resolve this follow these Four simple steps:
in the package.json file:
1- set the main field to the server file:
"main": "server.js" // <-- here set you server file
2- add the host parameter to the app.listen function
const port = process.env.PORT || 3000;
const host = '0.0.0.0'
app.listen(port, host, ()=> connsole.log(`server is running on port ${port}`)
3- add the postinstall script to package.json file
"scripts": {
"postinstall": "npm run build", // <-- add this line
"start": "node server.js" // <-- change server.js to you main file
}
4- add the engines field in package.json file
"engines": {
"node": ">=14.0.O", // <-- change it to your node version. you can "node -v" in you command line
"npm": ">=7.7.0" // <-- change this to your npm version. you can use "npm -v" in the command line to get your npm version
}
let me know if you have any succes with this!
Use process.env.PORT || 3000 for your port.
This will use Heroku's port when available or use port 3000 if it's not available (for example, local testing)
You can change 3000 to whatever you want, for example 8080
In your package.json file, in the scripts, make sure your start script contains -p $PORT.
Example of package.json (in this case, for NextJS app):
{
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p $PORT" // make sure to have -p $PORT in here
},
"dependencies": {
"typescript": "^4.3.2"
},
"devDependencies": {
"#next/eslint-plugin-next": "^11.1.2",
"#types/mongoose": "^5.11.97"
"typescript": "^4.3.2"
}
"license": "MIT"
}
I had same issue I could resolved issue with replace 'localhost' with IP which is '0.0.0.0'
In my case, neither the port nor the host was the problem. The index.js was divided into 2 files. server.js:
//server.js
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.resolve(__dirname, 'public')));
// and all the other stuff
module.exports = app
//app.js
const app = require('./server');
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
console.log('Server is running s on port: ' + port)
});
from package.json we ran node app.js.
Apparently that was the problem. Once I combined the two into one file, the Heroku app deployed as expected.
I have the same issue but my environment variables are set well and the version of npm and node is specified in package.json. I figured out it is because, in my case, Heroku needs "start" to be specified in package.json:
"scripts": {
"start": "node index.js"
}
After adding this to my package.json my node app is successfully deployed on Heroku.
While developing the application we need to define the PORT in the following way:
const port = process.env.PORT || 4000; // PORT must be in caps
And while deploying the app to server add the following method:
app.listen(port, () => {
console.info("Server started listening.");
});
We can pass hostname as second parameter while running it in local. But while deploying it to server the hostname parameter should be removed.
app.listen(port, hostName, () => {
console.info(`Server listening at http://${hostName}:${port}`);
});
My case was that I was running Database scripts on start up and were taking long time. I solved this by manually running npm start after deployment is complete.
A fixed number can't be set for port, heroku assigns it dynamically using process.env.PORT. But you can add them both, like this process.env.PORT || 5000. Heroku will use the first one, and your localhost will use the second one.
You can even add your call back function. Look at the code below
app.listen(process.env.PORT || 5000, function() {
console.log("Server started.......");
});
At of all the solution i have tried no one work as expected, i study heroku by default the .env File should maintain the convention PORT, the process.env.PORT, heroku by default will look for the Keyword PORT.
Cancel any renaming such as APP_PORT= instead use PORT= in your env file.
From the heroku bash process, pass down the value of $PORT to your node app using an options parser like yargs.
Here is an example of how you might do that. On the scripts object, inside package.json, add a start method "node server --port $PORT".
In your server file, use yargs to get the value from the port option (--port $PORT) of the start method:
const argv = require('yargs').argv;
const app = require('express')();
const port = argv.port || 8081;
app.listen(argv.port, ()=>{
console.log('Probably listening to heroku $PORT now ', argv.port); // unless $PORT is undefined, in which case you're listening to 8081.
});
Now when your app starts, it will bind to the dynamically set value of $PORT.
If, like me, you're configuring Heroku to run a script from your package.json file on deploy, make sure you haven't hard-coded the value of PORT in that script! If you do, you'll end up like me and spend an hour trying to figure out why you're getting this error.
I had same issue but with express and apollo-server. The solution from here:
The only special consideration that needs to be made is to allow
heroku to choose the port that the server is deployed to. Otherwise,
there may be errors, such as a request timeout.
To configure apollo-server to use a port defined by Heroku at runtime,
the listen function in your setup file can be called with a port
defined by the PORT environment variable:
> server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
> console.log(`Server ready at ${url}`); });
In my case I had two issues...
1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"
2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

App crashed after nodejs app is deployed to heroku [duplicate]

I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn't let me write so much code, so I would just say that the running the code locally as well within my network shows no issue.
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting for ');
console.log(request);
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
console.log(filePath);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(5000);
console.log('Server running at http://127.0.0.1:5000/');
Any idea ?
Heroku dynamically assigns your app a port, so you can't set the port to a fixed number. Heroku adds the port to the env, so you can pull it from there. Switch your listen to this:
.listen(process.env.PORT || 5000)
That way it'll still listen to port 5000 when you test locally, but it will also work on Heroku. Important note - PORT word must be capital.
You can check out the Heroku docs on Node.js here.
It's worth mentioning that if your code doesn't specify a port, then it shouldn't be a web process and probably should be a worker process instead.
So, change your Procfile to read (with your specific command filled in):
worker: YOUR_COMMAND
and then also run on CLI:
heroku scale worker=1
For those that are passing both a port and a host, keep in mind that Heroku will not bind to localhost.
You must pass 0.0.0.0 for host.
Even if you're using the correct port. We had to make this adjustment:
# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;
# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;
Then you can start the server, as usual:
app.listen(port, host, function() {
console.log("Server started.......");
});
You can see more details here: https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error
The error happens when Heroku failed to bind the port or hostname at server.listen(port, [host], [backlog], [callback]).
What Heroku requires is .listen(process.env.PORT) or .listen(process.env.PORT, '0.0.0.0')
So more generically, to support other environments, use this:
var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
console.log('Listening on port %d', server_port);
});
I had same issue while using yeoman's angular-fullstack generated project and removing the IP parameter worked for me.
I replaced this code
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
with
server.listen(config.port, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
In my case, I was using example from https://hapijs.com/
To fix the problem I replaced
server.connection({
host: 'localhost',
port: 8000
});
with
server.connection({
port: process.env.PORT || 3000
});
change this line
app.listen(port);
to
app.listen(process.env.PORT, '0.0.0.0');
it will work
While most of the answers here are valid, for me the issue was that I was running long processes as part of npm run start which caused the timeout.
I found the solution here and to summarize it, I just had to move npm run build to a postinstall task.
In other words, I changed this:
"start": "npm run build && node server.js"
to this:
"postinstall": "npm run build",
"start": "node server.js"
Come to think of this, it totally makes sense because this error (which used to appear occasionally) was becoming more and more common as my app kept growing.
Changing my listening port from 3000 to (process.env.PORT || 5000) solved the problem.
Restarting all dynos in heroku did the trick for me
In my case, I was using Babel with the babel-plugin-transform-inline-environment-variables plugin. Apparently, Heroku does not set the PORT env variable when doing a deployment, so process.env.PORT will be replaced by undefined, and your code will fallback to the development port which Heroku does not know anything about.
I realized that I don't need the port number in the request endpoint, so the endpoint was herokuapp.com and not herokuapp.com:5000.
The listen() call can be without host and callback:
server.listen(5000);
I Use ReactJs,
If you want upload to heroku add this in your webpack.config.js
Because if not add you will have error
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within
60 seconds of launch
//webpack.config.js add code like that
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
var server_port = process.env.YOUR_PORT || process.env.PORT || 5000;
var server_host = process.env.YOUR_HOST || "0.0.0.0";
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
devServer: {
disableHostCheck: true,
contentBase: "./ dist",
compress: true,
inline: true,
port: server_port,
host: server_host
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
I had the same issue because I didn't define Procfile. Commit a text file to your app's root directory that is named Procfile without a file extension. This file tells Heroku which command(s) to run to start your app.
web: node app.js
Edit package.json:
...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...
and Server.js:
...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...
I've spent a lot of hours to find the root cause, and eventually I've found that this timeout (60s) can be adjustable. Here you may change 60 second to 120 or even more. It works for me, hope will help anybody else!
To resolve this follow these Four simple steps:
in the package.json file:
1- set the main field to the server file:
"main": "server.js" // <-- here set you server file
2- add the host parameter to the app.listen function
const port = process.env.PORT || 3000;
const host = '0.0.0.0'
app.listen(port, host, ()=> connsole.log(`server is running on port ${port}`)
3- add the postinstall script to package.json file
"scripts": {
"postinstall": "npm run build", // <-- add this line
"start": "node server.js" // <-- change server.js to you main file
}
4- add the engines field in package.json file
"engines": {
"node": ">=14.0.O", // <-- change it to your node version. you can "node -v" in you command line
"npm": ">=7.7.0" // <-- change this to your npm version. you can use "npm -v" in the command line to get your npm version
}
let me know if you have any succes with this!
Use process.env.PORT || 3000 for your port.
This will use Heroku's port when available or use port 3000 if it's not available (for example, local testing)
You can change 3000 to whatever you want, for example 8080
In your package.json file, in the scripts, make sure your start script contains -p $PORT.
Example of package.json (in this case, for NextJS app):
{
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p $PORT" // make sure to have -p $PORT in here
},
"dependencies": {
"typescript": "^4.3.2"
},
"devDependencies": {
"#next/eslint-plugin-next": "^11.1.2",
"#types/mongoose": "^5.11.97"
"typescript": "^4.3.2"
}
"license": "MIT"
}
I had same issue I could resolved issue with replace 'localhost' with IP which is '0.0.0.0'
In my case, neither the port nor the host was the problem. The index.js was divided into 2 files. server.js:
//server.js
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.resolve(__dirname, 'public')));
// and all the other stuff
module.exports = app
//app.js
const app = require('./server');
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
console.log('Server is running s on port: ' + port)
});
from package.json we ran node app.js.
Apparently that was the problem. Once I combined the two into one file, the Heroku app deployed as expected.
I have the same issue but my environment variables are set well and the version of npm and node is specified in package.json. I figured out it is because, in my case, Heroku needs "start" to be specified in package.json:
"scripts": {
"start": "node index.js"
}
After adding this to my package.json my node app is successfully deployed on Heroku.
While developing the application we need to define the PORT in the following way:
const port = process.env.PORT || 4000; // PORT must be in caps
And while deploying the app to server add the following method:
app.listen(port, () => {
console.info("Server started listening.");
});
We can pass hostname as second parameter while running it in local. But while deploying it to server the hostname parameter should be removed.
app.listen(port, hostName, () => {
console.info(`Server listening at http://${hostName}:${port}`);
});
My case was that I was running Database scripts on start up and were taking long time. I solved this by manually running npm start after deployment is complete.
A fixed number can't be set for port, heroku assigns it dynamically using process.env.PORT. But you can add them both, like this process.env.PORT || 5000. Heroku will use the first one, and your localhost will use the second one.
You can even add your call back function. Look at the code below
app.listen(process.env.PORT || 5000, function() {
console.log("Server started.......");
});
At of all the solution i have tried no one work as expected, i study heroku by default the .env File should maintain the convention PORT, the process.env.PORT, heroku by default will look for the Keyword PORT.
Cancel any renaming such as APP_PORT= instead use PORT= in your env file.
From the heroku bash process, pass down the value of $PORT to your node app using an options parser like yargs.
Here is an example of how you might do that. On the scripts object, inside package.json, add a start method "node server --port $PORT".
In your server file, use yargs to get the value from the port option (--port $PORT) of the start method:
const argv = require('yargs').argv;
const app = require('express')();
const port = argv.port || 8081;
app.listen(argv.port, ()=>{
console.log('Probably listening to heroku $PORT now ', argv.port); // unless $PORT is undefined, in which case you're listening to 8081.
});
Now when your app starts, it will bind to the dynamically set value of $PORT.
If, like me, you're configuring Heroku to run a script from your package.json file on deploy, make sure you haven't hard-coded the value of PORT in that script! If you do, you'll end up like me and spend an hour trying to figure out why you're getting this error.
I had same issue but with express and apollo-server. The solution from here:
The only special consideration that needs to be made is to allow
heroku to choose the port that the server is deployed to. Otherwise,
there may be errors, such as a request timeout.
To configure apollo-server to use a port defined by Heroku at runtime,
the listen function in your setup file can be called with a port
defined by the PORT environment variable:
> server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
> console.log(`Server ready at ${url}`); });
In my case I had two issues...
1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"
2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

conflicting port numbers in react

I have a React app where I specified the port number in server.js as
const port = process.argv[3] || 3500;
At the bottom of the same file I wrote:
app.listen(port, () => console.log(`Web service running on port ${port}`));
While the app is able to run in my browser, unfortunately in the console of my text editor it says Web service running on port 3500 even when the url says localhost:3000.
I know that React uses port 3000 as default... but don't know why the app chose to use port 3000 instead of the port 3500 that I specified above.
To try and fix this I tried to install the dev dependency cross-env and in my package.json "start" script I specified cross-env PORT=3500.
After that change, I see that my React app is now running in the browser on Port 3500... but I am unable to avoid the message from the server.js file that says "Web service running on the Port # that I specified in the server.js file".
In server.js when I use const port = process.argv[3] || 3500; in conjunction with the cross-env port 3500 change in package.json... I get the message "Something is already running on Port 3500". So it seems impossible to get the correct console message that the React app is really running properly in the browser on Port 3500.
Full Express server.js below:
const jsonServer = require("json-server");
const chokidar = require("chokidar");
const cors = require("cors");
const fileName = process.argv[2] || "./data.js";
const port = process.argv[3] || 3500;
let router = undefined;
const app = express();
const createServer = () => {
delete require.cache[require.resolve(fileName)];
setTimeout(() => {
router = jsonServer.router(fileName.endsWith(".js")
? require(fileName)() : fileName)
}, 100)
}
createServer();
app.use(cors());
app.use(jsonServer.bodyParser)
app.use("/api", (req, resp, next) => router(req, resp, next));
chokidar.watch(fileName).on("change", () => {
console.log("Reloading web service data...");
createServer()
console.log("Reloading web service data complete.");
});
app.listen(port, () => console.log(`Web service running on port ${port}`));```
Express Server:
you can run express server in the any port you want it to run
const port = process.env.port || 4000 //? can be any port number
the console log you are getting in the editor is from the server and not from the react app.
React App:
by default react app runs in port 3000 if you want to change the Port of the react app then use react-scripts like this
"start": "set PORT= <Your Desired Port> && react-scripts start"
or you can set port directly from terminal like this
PORT=4000 npm start //? or any other port number
app.listen is for express servers. To run a react server use react-scripts. To change port number use the PORT environment variable.

openshift nodeJS app - git up to date/server running without errors but I still see welcome page

I am trying to host a nodeJS app that uses socket.io on OpenShift. I have created the app on openshift, used git clone to get the repo - I then edited server.js to look like this:
#!/bin/env node
var express = require('express');
var app = express()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
var osipaddress = process.env.OPENSHIFT_NODEJS_IP;
var osport = process.env.OPENSHIFT_NODEJS_PORT;
app.set('port', osport || 8000);
app.set('ipaddress', osipaddress);
/*var pf = require('policyfile').createServer();
pf.listen(10843, function(){
console.log(':3 yay')
});*/
server.listen(app.get('port'), app.get('ipaddress'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
app.use(express.static(__dirname + '/'));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/Startup.html');
});
io.configure(function() {
io.set('transports', ['websocket','xhr-polling']);
io.set('flash policy port', 10843);
//io.set('log level', 1);
});
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
console.log(data);
});
});
I then used git commit / git push to make the changes.
When I run rhc tail testapp the output does not produce any errors:
/Users/Eamon/.rvm/gems/ruby-2.0.0-p0/gems/highline-1.6.21/lib/highline/system_extensions.rb:230: warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777
DEBUG: Running node-supervisor with
DEBUG: program 'server.js'
DEBUG: --watch '/var/lib/openshift/53a2e6275973ca689c000060/app-root/data/.nodewatch'
DEBUG: --ignore 'undefined'
DEBUG: --extensions 'node|js|coffee'
DEBUG: --exec 'node'
DEBUG: Starting child process with 'node server.js'
DEBUG: Watching directory '/var/lib/openshift/53a2e6275973ca689c000060/app-root/data/.nodewatch' for changes.
info: socket.io started
Express server listening on port 8080
However, when I visit the site - I still see the initial welcome page (as if I had not pushed any code) - http://testapp-eamonbenproject.rhcloud.com/
Any ideas? As I am not really getting errors, I am not sure where to start.
Startup.html needed to be named index.html for openshift to work correctly.

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn't let me write so much code, so I would just say that the running the code locally as well within my network shows no issue.
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting for ');
console.log(request);
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
console.log(filePath);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(5000);
console.log('Server running at http://127.0.0.1:5000/');
Any idea ?
Heroku dynamically assigns your app a port, so you can't set the port to a fixed number. Heroku adds the port to the env, so you can pull it from there. Switch your listen to this:
.listen(process.env.PORT || 5000)
That way it'll still listen to port 5000 when you test locally, but it will also work on Heroku. Important note - PORT word must be capital.
You can check out the Heroku docs on Node.js here.
It's worth mentioning that if your code doesn't specify a port, then it shouldn't be a web process and probably should be a worker process instead.
So, change your Procfile to read (with your specific command filled in):
worker: YOUR_COMMAND
and then also run on CLI:
heroku scale worker=1
For those that are passing both a port and a host, keep in mind that Heroku will not bind to localhost.
You must pass 0.0.0.0 for host.
Even if you're using the correct port. We had to make this adjustment:
# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;
# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;
Then you can start the server, as usual:
app.listen(port, host, function() {
console.log("Server started.......");
});
You can see more details here: https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error
The error happens when Heroku failed to bind the port or hostname at server.listen(port, [host], [backlog], [callback]).
What Heroku requires is .listen(process.env.PORT) or .listen(process.env.PORT, '0.0.0.0')
So more generically, to support other environments, use this:
var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
console.log('Listening on port %d', server_port);
});
I had same issue while using yeoman's angular-fullstack generated project and removing the IP parameter worked for me.
I replaced this code
server.listen(config.port, config.ip, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
with
server.listen(config.port, function () {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
In my case, I was using example from https://hapijs.com/
To fix the problem I replaced
server.connection({
host: 'localhost',
port: 8000
});
with
server.connection({
port: process.env.PORT || 3000
});
change this line
app.listen(port);
to
app.listen(process.env.PORT, '0.0.0.0');
it will work
While most of the answers here are valid, for me the issue was that I was running long processes as part of npm run start which caused the timeout.
I found the solution here and to summarize it, I just had to move npm run build to a postinstall task.
In other words, I changed this:
"start": "npm run build && node server.js"
to this:
"postinstall": "npm run build",
"start": "node server.js"
Come to think of this, it totally makes sense because this error (which used to appear occasionally) was becoming more and more common as my app kept growing.
Changing my listening port from 3000 to (process.env.PORT || 5000) solved the problem.
Restarting all dynos in heroku did the trick for me
In my case, I was using Babel with the babel-plugin-transform-inline-environment-variables plugin. Apparently, Heroku does not set the PORT env variable when doing a deployment, so process.env.PORT will be replaced by undefined, and your code will fallback to the development port which Heroku does not know anything about.
I realized that I don't need the port number in the request endpoint, so the endpoint was herokuapp.com and not herokuapp.com:5000.
The listen() call can be without host and callback:
server.listen(5000);
I Use ReactJs,
If you want upload to heroku add this in your webpack.config.js
Because if not add you will have error
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within
60 seconds of launch
//webpack.config.js add code like that
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
var server_port = process.env.YOUR_PORT || process.env.PORT || 5000;
var server_host = process.env.YOUR_HOST || "0.0.0.0";
module.exports = {
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, "css-loader"]
}
]
},
devServer: {
disableHostCheck: true,
contentBase: "./ dist",
compress: true,
inline: true,
port: server_port,
host: server_host
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "index.html"
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
I had the same issue because I didn't define Procfile. Commit a text file to your app's root directory that is named Procfile without a file extension. This file tells Heroku which command(s) to run to start your app.
web: node app.js
Edit package.json:
...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...
and Server.js:
...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...
I've spent a lot of hours to find the root cause, and eventually I've found that this timeout (60s) can be adjustable. Here you may change 60 second to 120 or even more. It works for me, hope will help anybody else!
To resolve this follow these Four simple steps:
in the package.json file:
1- set the main field to the server file:
"main": "server.js" // <-- here set you server file
2- add the host parameter to the app.listen function
const port = process.env.PORT || 3000;
const host = '0.0.0.0'
app.listen(port, host, ()=> connsole.log(`server is running on port ${port}`)
3- add the postinstall script to package.json file
"scripts": {
"postinstall": "npm run build", // <-- add this line
"start": "node server.js" // <-- change server.js to you main file
}
4- add the engines field in package.json file
"engines": {
"node": ">=14.0.O", // <-- change it to your node version. you can "node -v" in you command line
"npm": ">=7.7.0" // <-- change this to your npm version. you can use "npm -v" in the command line to get your npm version
}
let me know if you have any succes with this!
Use process.env.PORT || 3000 for your port.
This will use Heroku's port when available or use port 3000 if it's not available (for example, local testing)
You can change 3000 to whatever you want, for example 8080
In your package.json file, in the scripts, make sure your start script contains -p $PORT.
Example of package.json (in this case, for NextJS app):
{
"private": true,
"scripts": {
"dev": "next dev -p 3001",
"build": "next build",
"start": "next start -p $PORT" // make sure to have -p $PORT in here
},
"dependencies": {
"typescript": "^4.3.2"
},
"devDependencies": {
"#next/eslint-plugin-next": "^11.1.2",
"#types/mongoose": "^5.11.97"
"typescript": "^4.3.2"
}
"license": "MIT"
}
I had same issue I could resolved issue with replace 'localhost' with IP which is '0.0.0.0'
In my case, neither the port nor the host was the problem. The index.js was divided into 2 files. server.js:
//server.js
const express = require('express')
const path = require('path')
const app = express()
app.use(express.static(path.resolve(__dirname, 'public')));
// and all the other stuff
module.exports = app
//app.js
const app = require('./server');
const port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', () => {
console.log('Server is running s on port: ' + port)
});
from package.json we ran node app.js.
Apparently that was the problem. Once I combined the two into one file, the Heroku app deployed as expected.
I have the same issue but my environment variables are set well and the version of npm and node is specified in package.json. I figured out it is because, in my case, Heroku needs "start" to be specified in package.json:
"scripts": {
"start": "node index.js"
}
After adding this to my package.json my node app is successfully deployed on Heroku.
While developing the application we need to define the PORT in the following way:
const port = process.env.PORT || 4000; // PORT must be in caps
And while deploying the app to server add the following method:
app.listen(port, () => {
console.info("Server started listening.");
});
We can pass hostname as second parameter while running it in local. But while deploying it to server the hostname parameter should be removed.
app.listen(port, hostName, () => {
console.info(`Server listening at http://${hostName}:${port}`);
});
My case was that I was running Database scripts on start up and were taking long time. I solved this by manually running npm start after deployment is complete.
A fixed number can't be set for port, heroku assigns it dynamically using process.env.PORT. But you can add them both, like this process.env.PORT || 5000. Heroku will use the first one, and your localhost will use the second one.
You can even add your call back function. Look at the code below
app.listen(process.env.PORT || 5000, function() {
console.log("Server started.......");
});
At of all the solution i have tried no one work as expected, i study heroku by default the .env File should maintain the convention PORT, the process.env.PORT, heroku by default will look for the Keyword PORT.
Cancel any renaming such as APP_PORT= instead use PORT= in your env file.
From the heroku bash process, pass down the value of $PORT to your node app using an options parser like yargs.
Here is an example of how you might do that. On the scripts object, inside package.json, add a start method "node server --port $PORT".
In your server file, use yargs to get the value from the port option (--port $PORT) of the start method:
const argv = require('yargs').argv;
const app = require('express')();
const port = argv.port || 8081;
app.listen(argv.port, ()=>{
console.log('Probably listening to heroku $PORT now ', argv.port); // unless $PORT is undefined, in which case you're listening to 8081.
});
Now when your app starts, it will bind to the dynamically set value of $PORT.
If, like me, you're configuring Heroku to run a script from your package.json file on deploy, make sure you haven't hard-coded the value of PORT in that script! If you do, you'll end up like me and spend an hour trying to figure out why you're getting this error.
I had same issue but with express and apollo-server. The solution from here:
The only special consideration that needs to be made is to allow
heroku to choose the port that the server is deployed to. Otherwise,
there may be errors, such as a request timeout.
To configure apollo-server to use a port defined by Heroku at runtime,
the listen function in your setup file can be called with a port
defined by the PORT environment variable:
> server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
> console.log(`Server ready at ${url}`); });
In my case I had two issues...
1) no listener at all because of running app from another entry file and this run script was deleted from package.json "scripts"
2) Case sensitive problem with 'Sequelize' instead of 'sequelize'

Resources