Sergei Basharov
Sergei Basharov

Reputation: 53850

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?

Upvotes: 8

Views: 1444

Answers (1)

furydevoid
furydevoid

Reputation: 1401

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.

Upvotes: 2

Related Questions