Friday, 11 October 2013

node.js Load and execute code at runtime

This is usefull when you have scripts you want to reload and execute at runtime.

function LoadJS(file, callback) {
console.log('Trying to load: ' + file);
fs.readFile(file, function(err, data) {
if (err) {
if (callback) callback(err, file);
} else {
try {
} catch (exception) {
console.log('Error loading ' + file, exception);
if (callback) callback(exception, file);
if (callback) callback(null, file);

Remember the contents of eval will be executed in global scope.
If you were using it through an object like
this.LoadJS = function(file, callback) { ...

Then before you could do something like this
var Something = this;

and in the js file you load
Something.W/e you want.

No comments:

Post a Comment