slightly_leaky.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // a trivial process that does nothing except
  2. // trigger GC and output the present base memory
  3. // usage every second. this example is intended to
  4. // demonstrate that memwatch itself does not leak.
  5. var http = require('http');
  6. var start = new Date();
  7. function msFromStart() {
  8. return new Date() - start;
  9. }
  10. var leak = [];
  11. // every second, this program "leaks" a little bit
  12. setInterval(function() {
  13. for (var i = 0; i < 10; i++) {
  14. var str = i.toString() + " on a stick, short and stout!";
  15. leak.push(str);
  16. }
  17. }, 1000);
  18. // meantime, the program is busy, doing *lots* of http requests
  19. var http = require('http');
  20. http.createServer(function (req, res) {
  21. res.writeHead(200, {'Content-Type': 'text/plain'});
  22. res.end('Hello World\n');
  23. }).listen(1337, '127.0.0.1');
  24. function doHTTPRequest() {
  25. var options = {
  26. host: '127.0.0.1',
  27. port: 1337,
  28. path: '/index.html'
  29. };
  30. http.get(options, function(res) {
  31. setTimeout(doHTTPRequest, 300);
  32. }).on('error', function(e) {
  33. setTimeout(doHTTPRequest, 300);
  34. });
  35. }
  36. doHTTPRequest();
  37. doHTTPRequest();
  38. var memwatch = require('../');
  39. // report to console postgc heap size
  40. memwatch.on('stats', function(d) {
  41. console.log("postgc:", msFromStart(), d.current_base);
  42. });
  43. memwatch.on('leak', function(d) {
  44. console.log("LEAK:", d);
  45. });
  46. // also report periodic heap size (every 10s)
  47. setInterval(function() {
  48. console.log("naive:", msFromStart(), process.memoryUsage().heapUsed);
  49. }, 5000);