Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restart node server on file change

I'm developing a node/express app

$> ./node_modules/babel/bin/babel-node.js index.js

Now I would like to reload the application if I make changes to index.js or any other dependency. How can I do this. I guess I have to use gulp for this, but than still I would like to have some advice on how to do this (which modules to use ect)

UPDATE: I've just tested with supervisor, but when something changes I get the following error:

$> /node_modules/.bin/supervisor --exec ./node_modules/babel/bin/babel-node.js index.js 

crashing child
Starting child process with './node_modules/babel/bin/babel-node.js     index.js'
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: listen EADDRINUSE
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1146:14)
    at listen (net.js:1172:10)
    at Server.listen (net.js:1257:5)

UPDATE: I just tried nodemon but I get the same errors as with supervisor:

$> nodemon  --exec ./node_modules/babel/bin/babel-node.js index.js  --watch libs

...
22 Aug 16:58:35 - [nodemon] restarting due to changes...
22 Aug 16:58:35 - [nodemon] starting `./node_modules/babel/bin/babel-   node.js index.js`
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: listen EADDRINUSE
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1146:14)
    at listen (net.js:1172:10)

UPDATE: I've solved the EADDRINUSE issue by adding the following to index.js

process.on('exit', () => {
    server.close();
})

process.on('uncaughtException', () => {
    server.close();

})

process.on('SIGTERM', () => {
    server.close();
})

However, now it seems to restart, but the new code is not loaded

like image 350
Jeanluca Scaljeri Avatar asked Dec 05 '22 20:12

Jeanluca Scaljeri


2 Answers

use this:

supervisor -- -r 'babel/register' index.js

and remove server.close code.

like image 105
Jhen-Jie Hong Avatar answered Dec 08 '22 11:12

Jhen-Jie Hong


I was really disappointed with the performance of all the solutions where you run babel-node within nodemon (or supervisor). So I built this:

https://github.com/kmagiera/babel-watch

You can use it as follows (perhaps in your package.json scripts section):

babel-watch -w src src/main.js

The difference is that instead of restarting whole babel-node process on every file change (which takes like 1.5sec on my MBP) it runs babel in parent process and starts "pure" node process with all transpiled JS files provided at your script startup.

like image 42
kzzzf Avatar answered Dec 08 '22 09:12

kzzzf