Advertisement
kernel

Cached require in node.js

Sep 27th, 2011
201
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function watchedRequire(file)
  2. {
  3.     var fs      = require('fs');
  4.     var path    = require('path');
  5.  
  6.     path.exists(file, function(exists) {
  7.         if(exists)
  8.         {
  9.             fs.watchFile(file, function(current, previous) {
  10.                 if(current.nlink === 0) // file does not exist anymore
  11.                 {
  12.                     delete(require.cache[file]);
  13.                     fs.unwatchFile(file);
  14.                     console.log('Deleted');
  15.                     return;
  16.                 }
  17.  
  18.                 if(current.mtime - previous.mtime) // has changed
  19.                 {
  20.                     delete(require.cache[file]);
  21.                     console.log('Changed');
  22.                     require(file); // rebuild cache with new file immediately
  23.                 }
  24.                 // console.log(require.cache);
  25.             });
  26.             return require(file);
  27.         }
  28.         throw new Error('File not found: '+file);
  29.     });
  30. }
  31.  
  32. var file = watchedRequire(process.cwd()+'/file.js');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement