Skip to content Skip to sidebar Skip to footer

How To Dynamically Load A Script (node Js)

So, in my nodeJS server part I need to use function from js file. This file often updated, so i need dynamic load this file every time, when client load page. How I can do this? Th

Solution 1:

Loading code from other files is done with require. However, once you've require'd a file, requiring it again will not load the file from disk again, but from a memory-cache which Node maintains. To reload the file again, you'll need to remove the cache-entry for your file before you call require on it again.

Say your file is called /some/path/file.js:

// Delete cache entry to make sure the file is re-read from disk.deleterequire.cache['/some/path/file.js'];
// Load function from file.var func = require('/some/path/file.js').func;

The file containing the function would look something like this:

module.exports = {
  func : function() { /* this is your function */ }
};

Solution 2:

In addition to @robertklep answer, here solution for any path:

const path = require('path');

var lib_path = './test'// <-- relative or absolute path                                                                  var file = require(lib_path);

constreset_cache = (file_path) => {
    var p = path.resolve(file_path);
    constEXTENTION = '.js';
    deleterequire.cache[p.endsWith(EXTENTION) ? p : p + EXTENTION];
}

// ... lib changed                                                                                                             reset_cache(lib_path);
file = require(lib_path); // file changed

Unfortunately, all dependencies of reloaded file didn't reload too.

Also, you can use clear-require module:

const clear_require = require('clear-require');

require('./foo');
// ... modifyclear_require('./foo');
require('./foo');

it can clear all modules, and handle regexp.

Post a Comment for "How To Dynamically Load A Script (node Js)"