user1965525
user1965525

Reputation:

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? Thanks!

Upvotes: 7

Views: 14251

Answers (3)

user3601435
user3601435

Reputation: 467

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);

const reset_cache = (file_path) => {
    var p = path.resolve(file_path);
    const EXTENTION = '.js';
    delete require.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');
// ... modify
clear_require('./foo');
require('./foo');

it can clear all modules, and handle regexp.

Upvotes: 7

user1965525
user1965525

Reputation:

This very simple script make me happy :) github.com/isaacs/node-supervisor

first:

npm install supervisor -g

second:

supervisor myapp.js

I have some error, but it's works.

Upvotes: -8

robertklep
robertklep

Reputation: 203286

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.
delete require.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 */ }
};

Upvotes: 8

Related Questions