Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload modules on the fly in Node REPL

I am testing my module with REPL like this:

repl.start({
    input: process.stdin,
    output: process.stdout
})
    .context.MyModule = MyModule;

Is there a way to reload the module automatically, when I change and save it, without having to exit and run repl again?

like image 567
Sergei Basharov Avatar asked Aug 31 '15 08:08

Sergei Basharov


Video Answer


1 Answers

You can use the chokidar module and force reload (you will lose runtime context in the module, but it should auto-reload).

var ctx = repl.start({
    input: process.stdin,
    output: process.stdout
})
    .context;

ctx.MyModule = require('./mymodule');

chokidar.watch('.', {ignored: /[\/\\]\./}).on('all', function(event, path) {
    delete require.cache['./mymodule'];
    ctx.MyModule = require('./mymodule');
});

If that doesn't work, I'm happy to play with it a little and get a working solution.


edit: if it doesn't garbage-collect cleanly (there are any open handles/listeners), this will leak each time it reloads. You may need to add a 'clean-exit' function to MyModule to stop everything gracefully, and then call that inside the watch handler.

like image 113
furydevoid Avatar answered Oct 19 '22 08:10

furydevoid