Node.js and Forever "exited with code: 0" - javascript

CentOs 6.5 using root acount, I have a working Node.js Express app:
root#vps [/home/test/node]# npm start app.js
> test#0.0.1 start /home/test/node
> node ./bin/www app.js
The app can be seen working on the internet browser. I stop the app and try to run it with forever:
root#vps [/home/test/node]# forever start app.js
warn: --minUptime not set. Defaulting to: 1000ms
warn: --spinSleepTime not set. Your script will exit if it does not stay up for at least 1000ms
info: Forever processing file: app.js
root#vps [/home/test/node]#
Throws a couple of warnings that should not be a problem and looks like it should be working but its not showing on the browser, forever list:
root#vps [/home/test/node]# forever list
info: Forever processes running
data: uid command script forever pid id logfile uptime
data: [0] OkGm /usr/local/bin/node app.js 32222 32227 /root/.forever/OkGm.log STOPPED
root#vps [/home/test/node]#
If I check OkGm.log:
error: Forever detected script exited with code: 0
Why is the app not working when I run it with forever?

Ok I found out what was happening. I was trying to run:
forever start app.js
When this Express app must be started with:
forever start ./bin/www
There was no useful info on internet when searching for this by the error log output ("exited with code: 0"), so I hope this answer helps begginers like me in what I think can be an easy mistake to make.

Related

Nodemon - "clean exit - waiting for changes before restart" during setup

I am trying to set up a RESTful API with Node and Postgres. I have run into a problem where whenever I attempt to run the server (using npm start) to test it locally, I get the following output:
[nodemon] 1.14.10 [nodemon] to restart at any time, enter rs [nodemon] watching: . [nodemon] starting node index.js server.js
[nodemon] clean exit - waiting for changes before restart
After searching online for quite some time, I cannot find too many resources on what exactly "clean exit - waiting for changes before restart" exactly means, especially in this case.
This is my queries.js file:
1 var promise = require('bluebird');
2
3 var options = {
4 // Initialization Options
5 promiseLib: promise
6 };
7
8 // created an instance of pg-promise, override default pgp lib w bluebird
9 var pgp = require('pg-promise')(options);
10 var connectionString = 'postgres://localhost:3000/actions';
11 var db = pgp(connectionString);
12
13 // add query functions
14
15 module.exports = {
16 getAllActions: getAllActions,
17 // getSingleAction: getSingleAction,
18 // createAction: createAction,
19 // updateAction: updateAction,
20 // removeAction: removeAction
21 };
22
23 function getAllActions(req, res, next) {
24 db.any('select * from acts')
25 .then(function (data) {
26 res.status(200)
27 .json({
28 status: 'success',
29 data: data,
30 message: 'Retrieved ALL actions'
31 });
32 })
33 .catch(function (err) {
34 return next(err);
35 });
36 }
Here is my index.js file:
3 var express = require('express');
4 var app = express();
5 var router = express.Router();
6 var db = require('./queries');
7
8 // structure: expressInstance.httpRequestMethod(PATH, HANDLER)
9 app.get('/api/actions', db.getAllActions);
10 //app.get('/api/actions/:id', db.getSingleAction);
11 //app.post('/api/actions', db.createAction);
12 //app.put('/api/actions/:id', db.updateAction);
13 //app.delete('/api/actions/:id', db.removeAction);
14
15 module.exports = router;
Any thoughts on what could be going on here? Thanks in advance.
There are a few things wrong with your code. You never told your app to run. When you're ready creating your routes you should start your server with:
app.listen(<port on which the server should run here>);
Also you have an Express app and a router in the same file. The router should only be used as a sub module (handy when you want to divide your app over multiple files). Right now you're doing nothing with it. If you remove the router and the export then it should work fine.
I am also wondering about this statement logged by nodemon. I experienced this only the last days. I get this error if some syntax error exists in my express server code. When I start the server via
> node server
the server does not start and even does not log anything to console.
Strange behaviour I think. It seems that this message has nothing to do with nodemon.
I never experienced such a thing with node in the past. Every time a syntax error was introduced I got an error message with the stack trace outputted to console.
As I said before it was just a syntax error: A closing bracket was missing from a .then block.
After all I do not know why node was not printing the stack trace as I have experienced it before.
I investigate further but one thing to learn from this kind of error is probably to use a linter for writing javascript code or go a step further and use TypeScript. I use TypeScript for developing the client with Angular and the possibilities to detect syntax errors early are great.
If anyone still has issues with this how I solved mine was that I discovered my database was not connected I'm using mongodb for my setup so setting up mongo with the mongod command and running the server again with either node app.js or nodemon app.js fixed mine
solution 1:
Firstly make sure you have included these lines of code for the Node-Express application,
// 3000 is the port number in my case.
app.listen(3000, function() {
console.log("Server is running on port " + 3000);
});
in your main file(i.e. app.js in my case) to start the server.
Solution 2:
Open your package.json file.
Check for the name of the file for the main field.
In my case it is
{...,"main": "app.js",...}.
This app.js is the primary entry point to the program.
Now, try to start your server with the following command,
nodemon app.js
or
node app.js
Solution 3:
If your program is running with,
node app.js
but, not with
nodemon app.js
Then, this problem is with nodemon.
If you have files with names as index.js and app.js in your project, then deleting index.js will resolve the issue.
If index.js is the entry point to your program, then try Solution 2 given above and change the main field value in the package.json file to index.js
i.e. {...,"main": "index.js",...}.
This will fix your issue.
I too had face the same issue.
Node version was 14.15.5.
so installed node 12.22 version and working fine.
I had the same issue but my problem was very simple newbie issue-adding it here in case those new to express and this type of code make the same mistake
I had unknowingly included the 'app.listen' within my 'app.get' code (yes I know, very basic mistake but it was frustrating, hence giving my option here)
Wrong way
app.get("/", (req, res) => {
res.send(req.query);
*....additional code here...*
app.listen(port, () => {
console.log("hey app is listening");
});
});
Right way-
app.get("/", (req, res) => {
res.send(req.query);
});
app.listen(port, () => {
console.log("hey app is listening");
});
Facing same problem, I just deleted the node_modules folder and package-lock.json file and reinstalled the dependencies and it worked.
app.listen(5010,function(){
console.log("server is running on port 5010");
});
// add the code above to resolve this issue
I had a similar issue after returning to one Node app (main file: app.js) after working on another Node app (main file: index.js).
If I entered
Nodemon app
I got a message like
[nodemon] starting `node app index.js`
[nodemon] clean exit - waiting for changes before restart
I played around with the version of Nodemon (update made no difference), I then tried entering
Node app
and got the usual proper working response, i.e.
[nodemon] 1.19.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`
HTTP server started at port 3000 ...
and I also got it going correctly when I entered
Nodemon app.js
Now, normally up to then it made no difference whether you enter app.js or app - but here it does seem to make a difference. Maybe some of the cached settings for the other Node app (i.e. the one using index.js as a main script and using app as an object within that file) were being retained and referenced to somehow.
Are there any Nodemon proficient people here to explain this ?
and your program will show the error on browser refused to connect than try this code on terminal if you using express generator
npm start
or
nodemon start
After many hours of looking for a solution why my production node-build in docker always immediately stops with exit 0 I found out that the node-version of the docker-images is incompatible. If you face this problem in docker try out different node-versions
[nodemon] starting node index.js
URI malformed
[nodemon] clean exit - waiting for changes before restart
I was able to fix this by changing the '#' symbol in my password for the connection url to %40
This is 2022, so if anyone still has this error, here's a fix that worked for me.
Make sure that your "start" command in "scripts" package.json is pointing to your entry file for the application.
`
"scripts": {
"dev": "nodemon src/server.ts",
"start": "nodemon dist/server.js",
"postinstall": "tsc"
}
`
Did you invoke start? For me that was a problem in app.js.
[nodemon] clean exit - waiting for changes before restart ?
Ans: Check your internet connection,
When restart my app my connection is lost thats why it will give the this err...

Node application does not restart though strong pm is running

We are using loopback to our node application using strong-pm as service on a production server. I used the following commands to run the application.
/sbin/initctl start strong-pm
/sbin/initctl status strong-pm
slc start
slc ctl set-size myapp 20
When node breaks, it does not restart and I need to run slc start again. Am I missing something here?

How do I get SocketCluster to restart on file change?

I'm running http://socketcluster.io/ and I want to restart my workers whewnever a file changes. However, nodemon server.js fails as soon as it tries to restart with an endlessly-repeating wall of:
1445633138359 - Origin: Worker (PID 44372)
[Error] Error: connect ECONNREFUSED /var/folders/fj/yzfd3_tn7xd0smz7j6s093mh0000gn/T/socketcluster/6879fe94-ed92-4188-b1d7-cb187a5ade4e_b68fcded6c/b0
at Object.exports._errnoException (util.js:874:11)
at exports._exceptionWithHostPort (util.js:897:20)
at PipeConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
1445633138362 - Worker 0 exited - Exit code: 0
How can I safely restart SocketCluster to load the new changes?
nodemon sends the SIGUSR2 signal to the main (Master) process. SocketCluster (correctly) interprets this as as a request to reboot the workers. Unfortunately, there's an open issue where things are not shut down properly and errors fly all around.
There are two options:
You can add the code from the linked issue:
house.addShutdownHandler(function(ctx, next){
socketCluster.killWorkers();
socketCluster.killBrokers();
next();
});
or use forever to send a "restart everything" signal:
forever -w --killSignal=SIGTERM server.js
Improvements were made for nodemon in SC version 5.0.23 or later.
Make sure that you pass killMasterOnSignal: true when instantiating SocketCluster in your code (server.js file) - This setting is necessary for nodemon to work.

why node.js process is killed?

I have developed one app in node.js. Recently I noticed when I am doing any changes in my "public" directory of my application, one error is recorded in my log file as follows:
error: restarting script because /home/{user}/workspace/{app_folder}/img/{filename}.jpg changed.
error: Forever detected script was killed by signal: SIGKILL
error: Forever restarting script for 1 time
Express server listening on port 3000
I have already set --watchIgnore parameter in my forever script file in /etc/init/{app}.config
env IGNORE_DIRECTORY="/home/{user}/workspace/{app_folder}/img/**"
exec forever --sourceDir $APPLICATION_DIRECTORY --watchIgnore $IGNORE_DIRECTORY \
-a -w -l $LOG --minUptime 5000 --spinSleepTime 2000 \
start $APPLICATION_START
What am I missing?
Note that the log shows {user} and not your actual user directory. This path looks like it was copied from a user guide, where you were meant to replace those quasi-variables with something.
You use bash environment variables (I assume you're using bash) like this:
env IGNORE_DIRECTORY="~/workspace/${APPLICATION_DIRECTORY}/img/**"
It looks like app_folder is actually defined for you as APPLICATION_DIRECTORY. You can also use ~/ as a shortcut for the current user's home folder.

Using nodejs's Forever to output console.logs to screen

I just discovered that my nodejs app keeps crashing, so I've used forever app.js to start my app and have it automatically restarted when it crashes.
Problem: Now my app outputs alot of useful information as it runs via console.log and util.log. I used to use screen to run the node app, but now that I'm using forever to run the nodejs app, I can no longer see all the outputs.
Is there any way to see all the output from the nodejs app in realtime?
Directly with forever command :
forever logs app.js -f
It shows in realtime output of your application and forever logs (shows detected changes & restart messages).
You can watch a logfile live by using this shell-command.
tail -f /path/to/logfile
Not sure if this is what you needed.
Simplest way to go is
Run :
forever logs // will give you list of log files
forever logs 0 -f // then just provide the index of log
If you pass the --help flag to Forever you'll see this example:
forever -o out.log -e err.log my-script.js
-o and -e define the stdout and stderr log files.
-o OUTFILE Logs stdout from child script to OUTFILE
-e ERRFILE Logs stderr from child script to ERRFILE
Forever seems a little overkill for development. Give Supervisor a shot and see if you like it better:
npm install -g supervisor
supervisor app.js
I am running nodejs on AWS EC2 instance and this worked for me.
Note: logs are accessible if you are root owner. So first use sudo su then
forever -a -o out.log -e err.log yourServerApp.js
It will tail console log (in case you track event messages from log) and error log. I hope it helps someone.
linux : tail -f /path/to/logfile.log
windows : enter PowerShell -> Get-Content /path/to/logfile.log -Wait -Tail 1000

Categories

Resources