I developed a few days ago a script to monitor node js applications. The wrong thing about it is that I have to exports manually each function that I want to monitor. For example, here is a piece of code I want to monitor :
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.setHeader('Content-Type', 'text/plain');
res.end('Home');
});
app.get('/login', function(req, res){
//On doit remplacer les appels de fonctions monitorées
//par le module.exports.fonction
//login(req,res);
exports.instrument_login(req, res)
});
function login(req, res){
res.setHeader('Content-Type', 'text/plain');
res.end('Page de login');
}
exports.instrument_login = login;
app.listen(1616);
All I have to do right now is to export the login function. Then my script will associate some AOP to it and I will be able to get the time of execution and the througput.
But, as you can see, I have to use exports.instrument_login(req, res) instead of login(req, res). I would be able to avoid this code replacement by listing directly every function in the app-script and then associate it to an AOP function. But then again, I just cannot figure it out.
Is it possible to do some kind of loop to go through every function in the app-script?
Someting like this :
Object.keys(object).sort(function( a, b ) {
return a.localeCompare( b );
}).forEach(function( element, index, array ) {
console.log(element);
});
But instead of object I would pass the object in Node JS which wrap every function?
You could just define your exports like this instead if you want to avoid having to write the exports.foo = bar; lines:
module.exports = {
instrument_login: function(req, res) {
res.setHeader('Content-Type', 'text/plain');
res.end('Page de login');
},
// other functions ...
};
If you are not in control of the code, you could use a JS AST module such as esprima (there are many others on npm that provide similar AST traversal functionality).
This would allow you to parse the javascript and look for functions. Then it would be trivial to just append exports.<functionName> = <functionName>; lines to the end of the script. You could then either save the result to a new file or overwrite the original if you want to be able to require() the modified code. Otherwise you could just emulate require() using the vm module, executing the modified code, and getting at the exported functions.