How to use the html-to-text.fromString function in html-to-text

To help you get started, we’ve selected a few html-to-text examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github codekirei / node-multispinner / extras / examples / cli-with-promises / index.js View on Github external
function printHtml(html) {
  console.log(
    h2t
      // html-to-text method
      .fromString(html, {
        ignoreImage: true,
        tables: true,
        wordwrap: false
      })
      // split into array of lines
      .split('\n')
      // trim whitespace
      .map(line => {
        return line.trim()
      })
      // remove duplicate consecutive lines
      .reduce((accum, line, i) => {
        if (line !== accum.slice(-1)[0]) accum.push(line)
        return accum
github fiatjaf / sitio / extract.js View on Github external
function extractSummary (content, ext) {
  var text = ext === 'html'
    ? toText.fromString(content, {ignoreHref: true, ignoreImage: true, wordwrap: 99999})
    : content

  var summary = ''

  var chars = text.split('')
  for (var i = 0; i < chars.length; i++) {
    var ch = chars[i]
    summary += ch
    if (ch === '\n' && chars[i + 1] === '\n' && summary.length > 300) {
      // paragraph
      break
    }
    if (ch === ' ' && summary.length >= 450) {
      // word break
      break
    }
github Mailtrain-org / mailtrain / server / lib / message-sender.js View on Github external
});
        }


        if (renderTags) {
            if (this.campaign) {
                html = await links.updateLinks(html, this.tagLanguage, mergeTags, campaign, list, subscriptionGrouped);
            }

            // When no list and subscriptionGrouped is provided, formatCampaignTemplate works the same way as formatTemplate
            html = tools.formatCampaignTemplate(html, this.tagLanguage, mergeTags, true, campaign, list, subscriptionGrouped);
        }

        const generateText = !!(text || '').trim();
        if (generateText) {
            text = htmlToText.fromString(html, {wordwrap: 130});
        } else {
            // When no list and subscriptionGrouped is provided, formatCampaignTemplate works the same way as formatTemplate
            text = tools.formatCampaignTemplate(text, this.tagLanguage, mergeTags, false, campaign, list, subscriptionGrouped)
        }

        return {
            html,
            text,
            attachments
        };
    }
github ecomfe / echarts-builder-web / css / font / build.js View on Github external
var text = ['index', 'echarts3', 'map3'].map(function (name) {
    return htmlToText.fromString(fs.readFileSync(path.join(__dirname, '../../' + name + '.html'), 'utf-8'));
}).join('');
// htmlToText.fromString(html, {}, function (err, text) {
github LessWrong2 / Lesswrong2 / packages / lesswrong / lib / search / utils.js View on Github external
};
  const postAuthor = Users.findOne({_id: post.userId});
  if (postAuthor) {
    algoliaMetaInfo.authorSlug = postAuthor.slug;
    algoliaMetaInfo.authorDisplayName = postAuthor.displayName;
    algoliaMetaInfo.authorUserName = postAuthor.username;
  }
  const postFeed = RSSFeeds.findOne({_id: post.feedId});
  if (postFeed) {
    algoliaMetaInfo.feedName = postFeed.nickname;
    algoliaMetaInfo.feedLink = post.feedLink;
  }
  let postBatch = [];
  let paragraphCounter =  0;
  let algoliaPost = {};
  const body = (post.content ? htmlToText.fromString(contentToHtml(post.content)) : (post.htmlBody ? htmlToText.fromString(post.htmlBody) : post.body))
  if (body) {
    body.split("\n\n").forEach((paragraph) => {
      algoliaPost = {
        ...algoliaMetaInfo,
        objectID: post._id + "_" + paragraphCounter,
        body: paragraph,
      }
      paragraphCounter++;
      postBatch.push(_.clone(algoliaPost));
    })
  } else {
    postBatch.push(_.clone(algoliaMetaInfo));
  }
  return postBatch;
}
github apostrophecms / apostrophe / lib / modules / apostrophe-email / index.js View on Github external
self.emailForModule = async function(req, templateName, data, options, module) {
      const transport = self.getTransport();
      const html = module.render(req, templateName, data);
      const text = htmlToText.fromString(html, {
        format: {
          heading: function(elem, fn, options) {
            let h = fn(elem.children, options);
            let split = h.split(/(\[.*?\])/);
            return split.map(function(s) {
              if (s.match(/^\[.*\]$/)) {
                return s;
              } else {
                return s.toUpperCase();
              }
            }).join('') + '\n';
          }
        }
      });
      const args = _.assign({
        html: html,
github academia-de-codigo / noire-server / lib / plugins / mailer.js View on Github external
exports.sendMail = async function(email) {
    Hoek.assert(internals.transporter, 'smtp transport not available');

    const { from, to, subject, template, context = {} } = email;
    const html = internals.templates[template](context);
    const text = HtmltoText.fromString(html);

    try {
        const info = await internals.transporter.sendMail({
            from,
            to,
            subject,
            html,
            text
        });

        Logger.child({ info }).debug('email has been delivered');
    } catch (error) {
        Logger.error(error);
        throw NSError.MAILER_ERROR();
    }
};
github timeoff-management / application / lib / model / db / user.js View on Github external
if ( ! email_obj ||
        ! email_obj.hasOwnProperty('subject') ||
        ! email_obj.subject ||
        ! email_obj.hasOwnProperty('body') ||
        ! email_obj.body
      ) {
        throw new Error(
          'Got incorrect parameters. There should be an object '+
          'to represent and email and contain subject and body'
        );
      }

      const promise_action = this.sequelize.models.EmailAudit.create({
        email      : this.email,
        subject    : htmlToText.fromString(email_obj.subject),
        body       : htmlToText.fromString(email_obj.body),
        user_id    : this.id,
        company_id : this.companyId,
      });

      return promise_action;
    },
github netlify / build / packages / netlify-plugin-search-index / index.js View on Github external
newManifest.map(async htmlFilePath => {
          const indexPath = path.relative(BUILD_DIR, htmlFilePath)
          const htmlFileContent = await pReadFile(htmlFilePath, 'utf8')
          const text = htmlToText.fromString(htmlFileContent, customOpts)
          searchIndex[`/${indexPath}`] = text
        }),
      )
github WaftTech / WaftEngine / client-ssr / htmlmanupulator.js View on Github external
internal.createHtml = (res, data, next) => {
  try {
    const { imagepath, description, title, url } = data;
    const text = htmlToText.fromString(description, {
      wordwrap: 130,
    });
    const html_replacer = `<title>${title}</title>`;
    const htmlContent = `${head}${html_replacer}${body}`;
    return res.send(htmlContent);
  } catch (err) {
    return next(err);
  }
};

html-to-text

Advanced html to plain text converter

MIT
Latest version published 12 months ago

Package Health Score

77 / 100
Full package analysis