Skip to content

Instantly share code, notes, and snippets.

@nfriedly
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfriedly/5813c0fcea944f05ccfe to your computer and use it in GitHub Desktop.
Save nfriedly/5813c0fcea944f05ccfe to your computer and use it in GitHub Desktop.
Log all fs.write* operations with a stack trace in node.js
// Stick this in the top of your main app.js/server.js/whatever file.
// Any time one of the below fs.* methods are called anywher in the app or dependencies,
// this code will log the details including the method, arguments, and a stack trace.
// It will then complete the write as normal.
var fs = require('fs');
['write','writeSync','writeFile','writeFileSync', 'appendFile', 'appendFileSync','createWriteStream'].forEach(function(fn){
fs['real'+fn] = fs[fn];
fs[fn] = function() {
var e = new Error();
console.log('fs.'+fn+' called with ' + Array.prototype.join.call(arguments, ', ') + ' Stack trace is:');
console.log(e.stack.split('\n').slice(2).join('\n')); // slice out the empty error and reference to this wrapper
return fs['real'+fn].apply(fs, arguments);
};
fs[fn].name = fn;
});
@nfriedly
Copy link
Author

nfriedly commented Aug 5, 2015

Note: this is now available in slightly-enhanced form as an npm module: https://www.npmjs.com/package/log-fs-writes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment