title: Get new email with node-imap nodejs
body: <p>I retrieved new email from a gmail account with node-imap. How do I keep a node-worker waiting for any new email and take an immediate action instead of cron jobs?</p>
  
  <p>I don't want to keep hitting the page every few minuets, kind of defeats the purpose of node js. </p>
  
  <p>Here's my code so far</p>
  
  <pre><code>var Imap = require('imap'),
  inspect = require('util').inspect;
  
  var imap = new Imap({
      user: 'yyyy@gmail.com',
      password: 'xxxx',
      host: 'imap.gmail.com',
      port: 993,
      tls: true,
      tlsOptions: { rejectUnauthorized: false }
  });
  
  var fs = require('fs'), fileStream;
  
  function openInbox(cb) {
      imap.openBox('INBOX', false, cb);
  }
  
  imap.once('ready', function() {
      openInbox(function(err, box) {
          if (err) throw err;
          imap.search([ 'UNSEEN', ['SINCE', 'October 2, 2013'] ], function(err, results) {
              if (err) {
                  console.log('you are already up to date');
              }
              var f = imap.fetch(results, { bodies: '' });
              f.on('message', function(msg, seqno) {
                  console.log('Message #%d', seqno);
                  var prefix = '(#' + seqno + ') ';
                  msg.on('body', function(stream, info) {
                      console.log(prefix + 'Body');
                      stream.pipe(fs.createWriteStream('msg-' + seqno + '-body.txt'));
                  });
                  msg.once('attributes', function(attrs) {
                      console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
                  });
                  msg.once('end', function() {
                      console.log(prefix + 'Finished');
                  });
              });
              f.once('error', function(err) {
                  console.log('Fetch error: ' + err);
              });
              f.once('end', function() {
                  console.log('Done fetching all messages!');
              });
          });
      });
  });
  
  
  
  imap.connect();
  </code></pre>