Categories
JavaScript Answers

How to convert HTML to PDF with Node.js?

To convert HTML to PDF with Node.js, we use Puppeteer.

For instance, we write

const puppeteer = require("puppeteer");
const handlebars = require("handlebars");

module.exports.htmlToPdf = async ({ templateHtml, dataBinding, options }) => {
  const template = handlebars.compile(templateHtml);
  const finalHtml = encodeURIComponent(template(dataBinding));

  const browser = await puppeteer.launch({
    args: ["--no-sandbox"],
    headless: true,
  });
  const page = await browser.newPage();
  await page.goto(`data:text/html;charset=UTF-8,${finalHtml}`, {
    waitUntil: "networkidle0",
  });
  await page.pdf(options);
  await browser.close();
};

to define the htmlToPdf function.

In it, we call launch to start a browser.

We call page.goto to go to the URL of the page we want to convert to a PDF.

Next we call pdf to convert it to a PDF.

Categories
JavaScript Answers

How to use MongoDB with promises in Node.js?

To use MongoDB with promises in Node.js, we use async and await.

For instance, we write

const main = async () => {
  let client, db;
  try {
    client = await MongoClient.connect(mongoUrl, { useNewUrlParser: true });
    db = client.db(dbName);
    const dCollection = db.collection("collectionName");
    const result = await dCollection.find();
    return result.toArray();
  } catch (err) {
    console.error(err);
  } finally {
    client.close();
  }
};

to call connect to connect to the Mongo database.

We call db to get the database.

We call collection to get the collection.

And we call find to return a promise with the collection data.

We call toArray to convert the data to an array.

Categories
JavaScript Answers

How to fix req.user Undefined with Node, Express and Passport?

To fix req.user Undefined with Node, Express and Passport, we add the Passport middlewares.

For instance, we write

app.use(session({ secret: "anything" }));
app.use(passport.initialize());
app.use(passport.session());

to add Passport into our Express app by calling app.use with the middlewares returned by passport.initialize and passport.session.

Categories
JavaScript Answers

How to add Where statement with date with Node Sequelize?

To add Where statement with date with Node Sequelize, we use operator properties.

For instance, we write

const { Op } = require("sequelize");

model.findAll({
  where: {
    start_datetime: {
      [Op.gte]: moment().subtract(7, "days").toDate(),
    },
  },
});

to call findAll to look for the entries with start_datetime bigger than or equal to 7 days before today.

We get the date with moment().subtract(7, "days").toDate().

Categories
JavaScript Answers

How to add optional splat param with Node Express.js routing?

To add optional splat param with Node Express.js routing, we use a question mark.

For instance, we write

router.get("/path/:id*?", (req, res, next) => {
  res.render("page", { title: req.params.id });
});

to call get to with the path of the route.

We make id an option parameter with ?.

And we get the id value with req.params.id.