When I run a nodejs server with the following command:
"start": "nodemon --max-old-space=8192 ./src/app.js --exec babel-node"
and I change anything in the code, nodemon automatically reloads the code and restarts the server with the following message.
[nodemon] restarting due to changes...
[nodemon] starting `babel-node --max-old-space=8192 ./src/app.js`
How do I restart the server manually the same way?
Or in other words: What do I write in the package.json scripts "restart" command to simulate the same behaviour that is done by nodemon automatically?
Thanks
As stated in the documentation, you can restart manually by typeing rs in the console where nodemon is running.
There is no external command to trigger a restart from a different process.
One workaround would be to trigger a restart by simulating a change of a file.
A simple touch on a watched file is enough. So you could write a npm script that touches one of the watched files.
"restart": "touch app.js"
The purpose of nodemon is to listen changes of the file and restart the server. If you want manually to restart the server then you no need to use nodemon, you can use just node command.
The below code would serve the purpose.
{
"scripts": {
"start": "node ./src/app.js",
"restart": "kill -9 $(ps aux | grep '\snode\s' | awk '{print $2}') && node ./src/app.js "
},
}
Tried a few things to restart nodemon from within a running script.
var fs = require('fs');
fs.utimesSync(__filename, Date.now(), Date.now());
This will touch the current file, which should trigger a restart if nodemon is watching.
Say goodbye to nodemon.
Node v18.11.0
Running in 'watch' mode using node --watch restarts the process when an imported file is changed.
try as follow:
node --watch app.js
For more information
Source: https://www.npmjs.com/package/nodemon
Manual restarting
Whilst nodemon is running, if you need to manually restart your
application, instead of stopping and restart nodemon, you can type rs
with a carriage return, and nodemon will restart your process.
If you are specifically looking to resolve "listen EADDRINUSE: address already in use" error after a while, you can check what application is using the port that nodemon wants to use:
sudo lsof -i :4500
The above will give you the PID of the app that is using that port. Then you may kill the process by:
kill -9 <PID>
Related
I am using the latest version of docker and the latest node image. I have a gulpfile that starts a nodemon process. I am using the --inspect flag to indicate I want to use the experimental chrome dev tool debugger. But when I make a file change it nodemon picks it up and restarts the process but crashes.
Here is my gulp task:
gulp.task('start:dev', done => {
let started = false;
nodemon({
script: path.join(__dirname, 'index.js'),
ext: 'js json',
nodeArgs: ['--inspect=0.0.0.0:9229'],
watch: path.join(__dirname, 'express'),
legacyWatch: true
})
.on('start', () => {
// to avoid nodemon being started multiple times
if (!started) {
setTimeout(() => done(), 100);
started = true;
}
});
});
And here is the error:
Starting inspector on 0.0.0.0:9229 failed: address already in use
If I change the --inspect flag to be --debug it works like a charm.
I am guessing is that the restart process is too fast for the --inspect to release its port. If I make another file change it does work and restarts normally. Probably since it had time to release the port.
I have tried using a delay on nodemon but I'd rather not. I would like quick restarts. And I have tried using to events, like, restart and exit, to wait for a few seconds and then restart the whole gulp task. But that was temperamental and again I want quick restarts without having to hack together something.
Right now I just switched back to --debug but that is deprecated in the latest V8. They are recommending to use --inspect.
Maybe the only way is to lock down my version of node?
Any suggestions?
There is an open issue addressing this problem.
The easiest workaround I found so far was using "signal": "SIGINT" in my nodemon.json thanks to this comment.
Just kill inspector and start inspector again
here is our team's solution in our package.json.
You had better kill inspector process and then restart inspector
"inspect": "kill-port --port 9229 && node --inspect=0.0.0.0:9229 build/startup.js",
"start_watch_inspect": `nodemon --delay 80ms --watch build/ build/startup.js --exec 'npm run inspect'`
Seems like this is related to:
https://github.com/remy/nodemon/issues/1492
My workaround is to run this before each restart: (in a makefile, gulp file etc...)
lsof -i -n | grep 9229 | awk '{print $2}' | xargs kill
** If put inside a Makefile remember to replace $ with $$ **
I have the following command:
/usr/local/bin/forever start -o /home/username/path/out.log -e /home/username/path/err.log /usr/local/bin/nodemon --watch /home/username/scriptpath --exitcrash /home/username/scriptpath/example.js
Which I understand should:
Run Forever as a daemon
Run Nodemon, which will restart the script when a change is seen in /home/username/scriptpath, and will also 'exit' to forever on crashing, allowing forever to restart it all.
However I'm observing Nodemon not restarting upon changes to the files in the watched folder. (Though forever is restarting on crash, when I intentionally cause one.)
Note: Running only "nodemon example.js" works as expected, and restarts on change to file.
What do I need to change to allow Nodemon to re-start the script upon file changes?
My knowledge of linux commands are limited unfortunately, I may well be using the wrong ones.
It will only watch changes in files that are liked to the script you are running by require.
For instance: forever ./script.js ...
var x = require("./test")
Will restart ./script if ./test is changed.
I use forever-service and nodemon.
Here is an example of how I use it to do all you mention.
This example does the following: everytime a json or raml file in the applications dist/assets folder is modified, wait 10 seconds and then restart the node app (server.js script):
forever-service install raml --script server.js -f " -c nodemon" -o " --delay 10 --watch dist/assets -e json,raml --exitcrash" -e "PATH=/usr/local/bin:$PATH"
It will also dump a log file to /var/log/raml.log
I hope that helps!
I am trying to use forever so that I can assure that my ExpressJS app will remain running constantly.
I am using Ubuntu 14.04 LTS.
Strangely, 'forever list' displays nothing, 'forever --version' displays nothing
I've tried:
forever start -c "npm start" ./
and:
forever start app.js
Without anything displayed.
If you are using node js with express framework then script will not start using :
forever start app.js
First stop all running apps:
forever stopall
When this Express framework used it must be started with:
forever start ./bin/www
and you should find this in package.json file:
"scripts": {
"start": "node ./bin/www"
}
I hope it helps you.
Currently is seems that for any code change in a sails.js app you have to manually stop the sails server and run sails lift again before you can see the changes.
I was wondering if there is any way when running in development mode to automatically restart the sails server when it detects a code change?
You have to use a watcher like forever, nodemon, or something else...
Example
Install forever by running:
sudo npm install -g forever
Run it:
forever -w start app.js
To avoid infinite restart because Sails writes into .tmp folder, you can create a .foreverignore file into your project directory and put this content inside:
**/.tmp/**
**/views/**
**/assets/**
See the issue on GitHub:
Forever restarting because of /.tmp.
You can use sails-hook-autoreload
Just lift your app as normal, and when you add / change / remove a model or controller file, all controllers and models will be reloaded without having to lower / relift the app.
For example with nodemon to watch api and config directories
.nodemonignore contents
views/*
.tmp/*
.git/*
Run the command after creating .nodemonignore
$> nodemon -w api -w config
Example for supervisor to ignore 3 directories
$> supervisor -i .tmp,.git,views app.js
If you're using Sails 0.11, you can install this hook to automatically reload when you change models or controllers (views do not require reloading):
npm install sails-hook-autoreload
https://www.npmjs.com/package/sails-hook-autoreload
install nodemon globally or locally.
npm install nodemon --save
npm install nodemon -g
install sails locally in you project as follows
npm install sails --save
then change package.json
from
"scripts": {
"debug": "node debug app.js",
"start": "node app.js"
},
to
"scripts": {
"debug": "node debug app.js",
"start": "node app.js",
"dev": "export NODE_ENV=development && nodemon --ignore 'tmp/*' app.js && exit 0"
},
then
npm run dev
I had the same problem and I have solved it using grunt-watch and grunt-forever with sails#beta tasks. The result is 4 grunt commands:
UPDATE: tasks are available in the current sails version (it's no longer beta :>)
start Starts the server
stop Stops the server
restart Restarts the server
startWatch Starts the server and waits for changes to restart it (using grunt-watch). This is probably your solution, but the other commands are also useful.
Here's the code - I'm using sails#beta, which includes a tasks directory, I don't know if this is included in previous versions:
First of all you have to install forever in your sails directory:
npm install grunt-forever --save-dev
tasks/config/forever.js Configure forever task.
module.exports = function(grunt) {
grunt.config.set('forever', {
server: {
options: {
index: 'app.js',
logDir: 'logs'
}
}
});
grunt.loadNpmTasks('grunt-forever');
};
tasks/config/watch.js (edit) Edit watch task in order to add a new rule
// api and assets default rules
,
server: {
// Server files to watch:
files: [
'api/**/*',
'config/**/*'
],
// Restart server
tasks: ['forever:server:restart']
}
tasks/register/watchForever.js Register your custom tasks (this file can be renamed to whatever you want)
module.exports = function(grunt) {
// Starts server
grunt.registerTask('start', [
'compileAssets',
'linkAssetsBuild',
'clean:build',
'copy:build',
'forever:server:start'
]);
// Restarts the server (if necessary) and waits for changes
grunt.registerTask('startWatch', [
'restart',
'watch:server'
]);
// Restarts server
grunt.registerTask('restart', [
'forever:server:restart'
]);
// Stops server
grunt.registerTask('stop', [
'forever:server:stop'
]);
};
With this you should be able to use
grunt startWatch
and make your server wait for changes to be restarted :>
Hope this helped!
Better you use
npm install -g nodemon
i am using this, and it will helps to improve my developing speed. no need to edit any files for this one!.
after installation
nodemon app.js
For anyone coming to this question now, it seems that this is no longer necessary - an application launched with sails lift will have a grunt watch task running, and code changes will be visible without a restart.
I didn't realise this was happening at first because there's nothing to indicate what's happening in the console, but it does seem to work without a restart (I'm using Sails 0.11)
Is there any way to have both of this packages running together?
So basically I want to have best from both worlds. Running server automatically (and restarting when there is an error) and also automatic updates when there is .js file change happening.
You should run something like this
forever start -c nodemon app.coffee
Toxa was on the right track, the issue that cfogelberg raised is valid, but to avoid that issue you can do the following:
forever -c "nodemon --exitcrash" app.js
this makes sure nodemon actually exits (rather than giving you the "app crashed" message) and then forever picks it up again.
In forever --help this -c specifies a command to run otherwise it defaults node. Without -c results in the error that is mention in the comments to this answer.
There is an entry about it in the nodemon FAQ:
If you're using nodemon with
forever (perhaps in a
production environment), you can combine the two together. This way if
the script crashes, forever restarts the script, and if there are file
changes, nodemon restarts your script. For more detail, see issue
30.
To achieve this you need to add the following on the call to
forever:
Use forever's -c nodemon option to tell forever to run nodemon instead of node.
Include the nodemon --exitcrash flag to ensure nodemon exits if the script crashes (or exits unexpectedly).
Tell forever to use SIGTERM instead of SIGKILL when requesting nodemon to stop. This ensures that nodemon can stop the watched node
process cleanly.
Optionally add the --uid parameter, adding a unique name for your process. In the example, the uid is set to foo.
bash forever start --uid foo --killSignal=SIGTERM -c nodemon
--exitcrash server.js
To test this, you can kill the server.js process and forever will
restart it. If you touch server.js nodemon will restart it.
To stop the process monitored by forever and nodemon, simply call the
following, using the uid we assigned above (foo):
bash forever stop foo
This will stop both nodemon and the node process it was monitoring.
Note that I would not recommend using nodemon in a production
environment - but that's because I wouldn't want it restart without my
explicit instruction.
I have not found a way of getting both packages running together. I tried to do #toxa's technique, but when my node.js app threw an exception nodemon would not automatically restart it, instead outputting an error message to the forever log:
nodemon] app crashed - waiting for file changes before starting...
However, forever has a -w option and the following command is effectively the same as if I'm running nodemon and forever together:
forever start -w my-app.js
The downside of forever -w versus nodemon: forever does not have a --delay option, so my server gets restarted once for each file that is changed.
I prefer a combo of what Toxa and Jubair suggest.
forever start -c nodemon app.coffee --exitcrash
If you need to pass arguments:
forever start -c "nodemon --harmony" app.js --exitcrash
I'm using forever-service . . .
This is what worked for me. It does the following: everytime a json or raml file in the applications dist/assets folder is modified, wait 10 seconds and then restart the node app (server.js script):
$ forever-service install raml --script server.js -f " -c nodemon" -o " --delay 10 --watch dist/assets -e json,raml --exitcrash" -e "PATH=/usr/local/bin:$PATH"
Then I can run:
$ service raml start|stop|restart|status
I can also have the service start on server reboot with the chkconfig utility:
$ chkconfig --add raml
$ chkconfig raml on
when using in the package.json use single quotes to make nodemon --existcrash as a single argument.
"start": "forever -c 'nodemon --exitcrash' server.js"
Output:
app_1 | [nodemon] app crashed
app_1 | error: Forever detected script exited with code: 1
app_1 | error: Script restart attempt #1
app_1 | [nodemon] 1.19.4
app_1 | [nodemon] to restart at any time, enterrs
app_1 | [nodemon] watching dir(s): *.*
app_1 | [nodemon] watching extensions: js,mjs,json
app_1 | [nodemon] startingnode /app/server.js`
app_1 | app is running on port 3000
`
Use like this: "start": "firever -c \"nodemon --exitcrash\" <main>.js"