如何从Node.js IMAP模块中的body获取纯文本

时间:2015-06-29 17:52:58

标签: javascript html node.js imap node-modules

我正在使用Node.js的IMAP模块来解析IMAP电子邮件的正文。我可以将身体作为原始HTML数据返回给我,但这包括标签和其他不必要的数据。我想要输入内容的文本(删除任何div,样式等)

以下是我目前使用的代码:

openInbox(function(err, box) {
      if (err) throw err;
      var f = imap.seq.fetch(box.messages.total + ':*', { bodies: ['HEADER.FIELDS (FROM)','TEXT'] });
      f.on('message', function(msg, seqno) {
        console.log('Message #%d', seqno);
        var prefix = '(#' + seqno + ') ';
        msg.on('body', function(stream, info) {
          if (info.which === 'TEXT')
            console.log(prefix + '\n\nBody [%s] found, %d total bytes\n\n\n', inspect(info.which), info.size);
          var buffer = '', count = 0;
          stream.on('data', function(chunk) {
            count += chunk.length;
            buffer += chunk.toString('utf8');
            if (info.which === 'TEXT')
              console.log(prefix + 'Body [%s] (%d/%d)', inspect(info.which), count, info.size);
          });
          stream.once('end', function() {
            if (info.which !== 'TEXT')
              console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
            else
              console.log(prefix + 'Body [%s] Finished', inspect(info.which));
            console.log('\n\n\n\n'+buffer.toString()+'\n\n\n\n\n\n');
          });
        });
        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.end();
      });
    });

有没有办法解析纯文本而没有任何标签或其他HTML信息?

1 个答案:

答案 0 :(得分:5)

有一个为此设计的节点模块: https://www.npmjs.com/package/html-to-text

var htmlToText = require('html-to-text');

var text = htmlToText.fromString('<h1>Hello World</h1>', {
    wordwrap: 130
});
console.log(text);

它也很好地将表解析为文本。