Is there a way to restart node server in runtime? - javascript

I am trying to define an endpoint in my express server that whenever this end point is called, the server restarts automatically in runtime.
for example, using express my server would look something like this ...
var express = require('express')
var app = express();
app.post('/restart', (req,res)=>{
//restart or create a new instance of the server
// then reply
res.json({
'message': 'server restarted successfully'
})
})
// =======================
// start the server ======
// =======================
var port = process.env.PORT || 8000;
app.listen(port);
console.log('server running at http://localhost:' + port);
NOTE: Although I am using expressJS, I am open to other solutions like HAPI for example.
Thanks in advance

The only way I know of how to restart a node instance is in the CLI level via npm forever or the pm2, but this is for deployment level xP.

You would need npm module forever to be globally installed on your system and Shelljs as a dependency. Initially start your server as forever start {Path to server.js}. Then you can do
var express = require('express')
var shell = require('shelljs')
var app = express();
app.post('/restart', (req,res)=>{
//restart or create a new instance of the server
shell.exec('forever restart {Path to server.js}');
// then reply
res.json({
'message': 'server restarted successfully'
})
})
// =======================
// start the server ======
// =======================
var port = process.env.PORT || 8000;
app.listen(port);
console.log('server running at http://localhost:' + port);
Also see that you will not get a response as the server would have restarted. You would just get a refused to connect.

You can use PM2 to start, stop your server using simple commands.
Starting an application in production mode is as easy as:
pm2 start app.js
Stop all apps
pm2 stop all
Restart all apps
pm2 restart all
I hope this will work for you.
HTH Thanks!

Since express uses the HTTP from Node, you might initialize the Express server by yourself with the Node HTTP functions, noted here.
Once you have the server started, you might close it and restart it as you wish, as mentioned here.
Just you have to be careful with the already opened connections, as calling the HTTP instance for close will leave the already opened connection(s) still open. More information about closing them all; can be found here.

Related

How do I deploy node app to heroku without using Express

I deployed my node.js app successfully to heroku however when I accessed the site there was an error saying
"Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch"
my code is
var router = require("./router.js");
// Create a web server
var http = require("http");
http.createServer(function (request, response) {
router.home(request, response);
router.user(request, response);
}).listen(1337);
console.log("Sever running at http://127.0.0.1:1337/");
I figured it has something to do with the port. There was a post similar to my problem Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)
but their solutions were based on Express. I didn't use express for my app.
Is there any other way to not set the port to a fixed number?
It doesn't matter if you use express or not. Herouku binds a port for you in the process.env.PORT environment variable. You need to use that like so:
var port = process.env.PORT || 1337
Then use .listen(port)
Make sure you're connecting to the correct port in your browser (log the port to console to be sure)

How to start a .js file after it is stopped

i was looking to make a file / script that will restart a .js file after it has been stopped. after it is stopped, i want the new file to enter a command somewhere along the lines of this: nodejs server.jsin my VPS window .
so what i am getting at is like this:
1) i have my server.js up and running on my VPS with the command; nodejs server.js
2) it will automatically stop (I have this part down)
3) i want to have another script that restarts the node.js server after it has been stopped.
sorry if i am jumbling my words, or asking a silly question, just not sure how to go about this!
Thanks!
install module node-cmd in project directory
suppose you have too file server.js and app.js which listen on two different port
keep both file in same directory(not mandatory but to run with out path confusion )
server.js
const app = require('express')();
app.get('/',function(req,res){
res.send("running");
});
var cmd=require('node-cmd');
cmd.run('node server.js');
app.listen(8080);
console.log('listening on port 8080');
app.js
const app = require('express')();
app.get('/',function(req,res){
res.send("support file which will start server.js");
});
var cmd=require('node-cmd');
cmd.run('node server.js');
app.listen(8090);
console.log('listening on port 8090');
call app.js when you want to run server.js
nodemon usage is for when you change your server code or any code of your project then automaticaly restart server so when the app crashed it does not restart your server.js until you dont have a change in your codes so you need to use a package like forever or pm2 that start server continuously forever and if your app crashs then they will restart your server.js just after a few miliseconds here is the documentation :
https://github.com/foreverjs/forever
http://pm2.keymetrics.io/

Why isn't my node app logging to the terminal or the Chrome console?

I'm a noob when it comes to back-end with Node.
I'm running this file on an Ubuntu 14 server in the cloud. The file is being run with pm2. (ex. pm2 start newServer). The outputs from the console.log()s aren't appearing either in the terminal I've ssh'd into or in the javascript console in the browser. How can I get the file to log output into the terminal I've ssh'd into? Or am I going about this the wrong way entirely (do I need to start learning unit testing, is there some logging module I should be using, ...?)
EDIT: The pm2 logs (viewed with 'pm2 logs' or 'pm2 logs [app name]) don't contain any of the output from the console.log statements in the node script.
EDIT2: I also don't get log output anywhere when I stop the pm2 process and just run the file with node.
EDIT3: Still no output when I run the script with node on my local machine and access the page in the browser via localhost:8080.
FINAL EDIT: Figured it out. It's because my gulpfile had strip-debug in it. Being new to build systems, I didn't realize that said option removed console.logs. I found out by using node-inspector to actually look at the node code that was being run, and finding that my console.log statements had been replaced with "void 0"s.
var express = require('express'); //Require express for middleware use
const app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http); //IO is the server
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
//BASICS
app.use(express.static(__dirname + "/served")); //Serve static files
app.get('/', function(req, res){
res.sendFile('./index.html');
});
io.on('connection', function(socket){
// socket.on('chat message', function(msg){
// io.emit('chat message', msg);
// });
console.log("A user connected: ", socket.id);
});
http.listen(8080, function(){
console.log('listening on *:8080');
});
console.log('test')
// MONGODB
var url = 'mongodb://localhost:27017/test';
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server.");
db.close();
});
I'm not an expert on pm2, but from a quick glance it's designed for production use, and won't log anything to the terminal.
Looking at the page
https://github.com/Unitech/pm2
There is a section on Log facilities which tells you how to look at the logs, with a command like this
pm2 logs APP-NAME # Display APP-NAME logs
Otherwise if you really just want to see what it is doing, just run your code with node, eg
node myprogram.js
When using the pm2 module the logs are saved per separate node. In order to view them you can issue the command pm2 logs to view the logs for each node.

Socket.io-client simple client/server test wont connect - Node.js

I am trying to get some simple communication to work in Node.js using socket.io and socket.io-client.
I have two scripts, server.js and client.js.
The server.js script can bind to a webfacing port and act like a normal server/socket.io host, which all works when used with the browser client,
but the client.js (running in another node script) doesn't work, it just waits not outputting anything. I expect my socket.io-client in client.js to connect to the socket.io instance in server.js and for both to display a message in their console to say they're connected.
server.js code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
console.log("\nNew server request: "+req.url+"\n");
// sends a html file with a script that connects
// to socket.io running in server.js
res.sendFile(__dirname+'/webroot/index.html');
});
// listens for connections
io.on('connect', function(socket){
console.log('a client connected');
});
// start listening on server
http.listen(9000, function(){
console.log('listening: 9000');
});
client.js code:
var io = require('socket.io-client');
// connect to server.js socket
var socket = io('http://hostsite.com', {
port: 9000
});
socket.on('connect', function(){
console.log("connected\n");
});
installed with npm
npm install socket.io // version: 1.0.6
npm install socket.io-client // version: 1.0.6
npm install express // version: 4.8.5
Ideally I don't want to be using express or an http server, just a socket communication between two Node.js scripts, one on a server machine, one on a client machine.
Thanks for any help :)
For some reason, it wouldn't connect when i used:
npm install socket.io-client
and
require('socket.io-client');
But it does connect if I use the client that comes with the main package
npm install socket.io
and
require('socket.io/node_modules/socket.io-client');
Took a while to figure out, but hopefully now it will take someone else less time; if they face the same problem.
have you tried:
var socket = io.connect('http://hostsite.com:9000');

Node.js/Express.js App Only Works on Port 3000

I have a Node.js/Express.js app running on my server that only works on port 3000 and I'm trying to figure out why. Here's what I've found:
Without specifying a port (app.listen()), the app runs but the web page does not load.
On port 3001 (app.listen(3001)) or any other port that is not in use, the app runs but the web page does not load.
On port 2999, the app throws an error because something else is using that port.
On port 3000, the app runs and the web page loads fine.
I know that Express apps default to port 3000. But strangely, my app only runs when I explicitly make it run on port 3000 (app.listen(3000)).
I found this on line 220 of /usr/bin/express:
app.set(\'port\', process.env.PORT || 3000);
Which is doing as previously stated: setting the port to what is specified or to 3000 if nothing is specified.
How could I make my app work on a different port such as 8080 or 3001?
Thanks!
Edit: Code Sample (Very Simple Node/Express App)
var express = require("express");
var app = express();
app.get('/', function(req, res){
res.send('hello world');
});
// Only works on 3000 regardless of what I set environment port to or how I set [value] in app.set('port', [value]).
app.listen(3000);
The following works if you have something like this in your app.js:
http.createServer(app).listen(app.get('port'),
function(){
console.log("Express server listening on port " + app.get('port'));
});
Either explicitly hardcode your code to use the port you want, like:
app.set('port', process.env.PORT || 3000);
This code means set your port to the environment variable PORT or if that is undefined then set it to the literal 3000.
Or, use your environment to set the port. Setting it via the environment is used to help delineate between PRODUCTION and DEVELOPMENT and also a lot of Platforms as a Service use the environment to set the port according to their specs as well as internal Express configs. The following sets an environment key=value pair and then launches your app.
$ PORT=8080 node app.js
In reference to your code example, you want something like this:
var express = require("express");
var app = express();
// sets port 8080 to default or unless otherwise specified in the environment
app.set('port', process.env.PORT || 8080);
app.get('/', function(req, res){
res.send('hello world');
});
// Only works on 3000 regardless of what I set environment port to or how I set
// [value] in app.set('port', [value]).
// app.listen(3000);
app.listen(app.get('port'));
In bin/www, there is a line:
var port = normalizePort(process.env.PORT || '3000');
Try to modify it.
Try this
$ PORT=8080 node app.js
Try to locate the bin>www location and try to change the port number...
The default way to change the listening port on The Express framework is to modify the file named www in the bin folder.
There, you will find a line such as the following
var port = normalizePort(process.env.PORT || '3000');
Change the value 3000 to any port you wish.
This is valid for Express version 4.13.1
Just a note for Mac OS X and Linux users:
If you want to run your Node / Express app on a port number lower than 1024, you have to run as the superuser:
sudo PORT=80 node app.js
In the lastest version of code with express-generator (4.13.1) app.js is an exported module and the server is started in /bin/www using app.set('port', process.env.PORT || 3001) in app.js will be overridden by a similar statement in bin/www.
I just changed the statement in bin/www.
Noticed this was never resolved... You likely have a firewall in front of your machine blocking those ports, or iptables is set up to prevent the use of those ports.
Try running nmap -F localhost when you run your app (install nmap if you don't have it). If it appears that you're running the app on the correct port and you can't access it via a remote browser then there is some middleware or a physical firewall that's blocking the port.
Hope this helps!
The line you found just looks for the environmental variable PORT, if it's defined it uses it, otherwise uses the default port 3000. You have to define this environmental variable first (no need to be root)
export PORT=8080
node <your-app.js>
If you want to show something you're connected on 3000
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
I hope that will be helpful to you
Answer according to current version of express
If you talk about the current version of express, if you run app.listen() to start listening without specifying port, Express will chose a random port for your application, to find out about which port it is currently running on use
app.listen(0, () => {
console.log(app.address().port)
}
should output the port of your app. Moreover that first parameter 0 can be totally ignored but is not recommended
In app.js, just add...
process.env.PORT=2999;
This will isolate the PORT variable to the express application.
I am using the minimist package and the node startup arguments to control the port.
node server.js --port 4000
or
node server.js -p 4000
Inside server.js, the port can be determined by
var argv = parseArgs(process.argv.slice(2))
const port = argv.port || argv.p || 3000;
console.log(`Listening on port ${port}...`)
//....listen(port);
and it defaults to 3000 if no port is passed as an argument.
You can then use listen on the port variable.
Make sure you are running from that folder of your application, where you have the package.json.
I think the best way is to use dotenv package and set the port on the .env config file without to modify the file www inside the folder bin.
Just install the package with the command:
npm install dotenv
require it on your application:
require('dotenv').config()
Create a .env file in the root directory of your project, and add the port in it (for example) to listen on port 5000
PORT=5000
and that's it.
More info here
If you are using Nodemon my guess is the PORT 3000 is set in the nodemonConfig.
Check if that is the case.

Categories

Resources