docker node app always crashes on file change using nodemon - node.js

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 $$ **

Related

Nodejs waiting for 127.0.0.1:9229 to be free

When I try to use debugger in node to open debugger, I get an error 'Timeout (2000) waiting for 127.0.0.1:9229 to be free'. How can I resolve this and run the debugger correctly ?
function foo() {
var a = 5;
debugger
console.log(a)
}
foo()
I have already tried changing the port using node inspect --port=9230 app.js and it doesn't work.
Try this:
node --inspect-brk app.js
replace app.js with your file name that you want to run, and you can insert your additional command alongside with this line.
I had the same problem, it took me hours to figure it out...
Run the following command:
node inspect --port=9228 file.js
I had the same issue by using VS Code. VS code document helps. Replace program.js with your js file name.
https://code.visualstudio.com/docs/nodejs/nodejs-debugging
if the program should not start running but must wait for the debugger to attach:
node --inspect-brk program.js
Use node --inspect-brk {js file name} instead. It will work.
--inspect-brk=[host:port]
Enable inspector agent
2.Bind to address or hostname host (default:127.0.0.1)
3.Listen on port port (default: 9229)
4.Break before user code starts
I think the issue here is the command you give to node, it should be node --inspect..
You are missing the -- in front of inspect :)
Install
npm install --global node-inspect
Then
node-inspect script.js
Ref: https://www.npmjs.com/package/node-inspect

How to properly restart nodemon server

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>

Grunt message: Fatal error: Port 35729 is already in use by another process

Grunt was working. But after moving my site's files up one directory, to sit at root, grunt stopped working:
Fatal error: Port 35729 is already in use by another process.
Would the path matter in this case? Looking at port 35729, I found that Grunt was the only process running on that port. I killed that process, confirmed that no other process was running on 35729, then ran grunt again, but still getting that same fatal error as before.
Although none of my config files changed for grunt since it was working, I thought I'd try using the "npm init" approach to create a new package.json, then run "npm install" again and confirmed it downloaded "node_modules". What else can I try?
I'm running Node v0.10.33 on Mac OS 10.10.5
Dont stop a process with Ctrl+C in the terminal.
Ctrl+Z will keep it running.
Find the process id by sudo lsof -i :35729
Then kill the process by sudo kill -9 PID
Rerun the grunt watch
Grunt watch was already running in a different project in my case. So I updated Grunt's watch task appropriately for live reload to watch on a different port.
watch: {
main: {
options: {
livereload: 35730,
livereloadOnError: false,
spawn: false
},
files: [createFolderGlobs(['*.js', '*.less', '*.html']), '!_SpecRunner.html', '!.grunt'],
tasks: [] //all the tasks are run dynamically during the watch event handler
}
}
Specified livereload:PORT
The problem is grunt-contrib-watch's live reload: https://github.com/gruntjs/grunt-contrib-watch/blob/v1.0.0/tasks/lib/livereload.js#L19
You can't have two grunt-watch with the livereload option set to true. Either set one of the livereload options to false or change the port of liverelaod to something else by setting the livereload option from true to other value than 35729, like live-reload: 1337.
See the docs for more: https://github.com/gruntjs/grunt-contrib-watch#optionslivereload
Otherwise, you can run as many grunt processes as you want.
Problem solved. Although grunt-cli is installed globally, grunt gets installed locally with the project. So when I moved my site's files up one directory, and ran grunt from that new location, I was effectively launching a second instance of grunt, which found the port already occupied of course, by the earlier instance of grunt launched before moving files.
After I killed that process, grunt ran without a problem. I wasn't able to kill it using kill -9 so I used the Mac's Activity Monitor to issue "Force Quit".
solution :
Step 1
Run command-line as an Administrator. Then run the below mention command. Type your port number in yourPortNumber:
netstat -ano | findstr : (yourPortNumber)
Step 2
Then you execute this command after identify the PID.
taskkill /PID (typeyourPIDhere) /
Enjoy Coding !

Nodemon + Forever not detecting changes to files

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!

Auto reloading a Sails.js app on code changes?

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)

Resources