简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM