8

In my NodeJS server, I need to use a function from a JS file. This file is often updated, so I need to dynamically load this file every time when client load page. How I can do this? Thanks!

0

3 Answers 3

8

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 */ }
};
Sign up to request clarification or add additional context in comments.

2 Comments

so, i have this i.imgur.com/7BHePHS.png i.imgur.com/85TigEB.png and this not working :(
require.cache probably contains the full path name, console.log(require.cache) somewhere to find out how exactly your file is stored in it.
8

In addition to @robertklep's answer, here is a 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 the reloaded file didn't reload too.

Also, you can use the clear-module package:

const clear_module = require('clear-module');

require('./foo');
// ... modify
clear_module('./foo');
require('./foo');

It can clear all modules and handle regexp.

Comments

-8

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.

2 Comments

Very poor explanation! What kind of erros did you got?
why is this accepted?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.