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!
3 Answers
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 */ }
};
2 Comments
require.cache probably contains the full path name, console.log(require.cache) somewhere to find out how exactly your file is stored in it.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
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.