Categories
JavaScript Answers Nodejs

How to Get an Image from the Web and Encode it into a Base64 String with Node.js?

To get an image from the web and encode it into a base64 string with Node.js, we can use the Axios HTTP client to get the image and save it in a buffer object.

Then we can convert the saved buffer object into a base64 string.

To install Axios, we run:

npm i axios

Then we write:

const axios = require('axios')

const getImage = async () => {
  const image = await axios.get('https://picsum.photos/200/300', {
    responseType: 'arraybuffer'
  });
  const returnedB64 = Buffer.from(image.data).toString('base64');
  console.log(returnedB64)
}
getImage()

to import the axios package.

And then we create the getImage function that calls axios.get to make a GET request to get the image.

The 2nd argument sets the responseType to 'arraybuffer' so the image will be assigned to an array buffer with the image.

Next, we call Buffer.from with image.data to convert the array buffer object to a buffer.

Then we call toString with 'base64' to convert the buffer object to a base64 string and assign that to the returnedB64 variable.

Categories
JavaScript Answers Nodejs

How to Convert HTML to PDF with Node.js?

To convert HTML to PDF with Node.js, we can use the html-pdf library.

To use the library, we first install it by running:

npm i html-pdf

Then, we can write:

const pdf = require('html-pdf');
const html = `<b>hello world</b>`
const options = {
  format: 'Letter'
}

pdf.create(html, options).toFile('./pdfname.pdf', (err, res) => {
  if (err) {
    console.log(err);
  }
});

to use it by importing the library.

Then we add the html variable with the HTML string that we want to convert to a PDF file.

Next, set the options variable to an object that has some options for how to render the PDF.

Then we call pdf.create with html and options to render the HTML into a PDF with the given options.

The toFile method takes the file path to save the PDF to and a callback that runs when the PDF conversion is done.

err is defined when there’s an error with converting the PDF.

Therefore, we should see hello world in bold in the rendered PDF.

Categories
Express JavaScript Answers

How to Add a Single Routing Handler for Multiple Routes in a Single Line with Express?

To add a single routing handler for multiple routes in a single line with Express, we can pass in an array of route path patterns that will be handled by one route handler.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

const routes = ['/', '/foo', '/bar', '/baz/:id']
app.get(routes, (req, res) => {
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We have the routes array that has strings with different route path patterns.

And we use it as the first argument of the app.get method.

Therefore, when we go to / , /foo , /bar or /baz with anything after it, we’ll see hello world displayed.

This also works with app.post , app.delete , app.put , and other route defining methods.

Categories
Express JavaScript Answers

How to Accept Multiple URL Parameters in Express Routes?

To accept multiple URL parameters in Express routes, we can put them as the placeholders for each URL parameter in the route path string.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('hello world')
});

app.get('/fruit/:fruitName/:fruitColor', (req, res) => {
  const {
    fruitName,
    fruitColor
  } = req.params
  res.json({
    fruitName,
    fruitColor
  });
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We add the ‘/fruit/:fruitName/:fruitColor’ route, where :fruitName and :fruitColor are the URL params placeholders.

We can get the values of them from the req.params object.

Then, we return the extracted parameter values in the response object with res.json .

So if we make a GET request to /fruit/apple/green , we see:

{
    "fruitName": "apple",
    "fruitColor": "green"
}

returned as the response.

Categories
Express JavaScript Answers

How to Get Raw Request Body with Express?

To get raw request body in our Express app, we can add the raw body parsing function and set that as the value of the verify option of the middleware.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser');

const rawBodySaver =  (req, res, buf, encoding) =>{
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8');
  }
}

const options = {
  verify: rawBodySaver
};

app.use(bodyParser.json(options));

app.post('/', (req, res) => {
  console.log(req.rawBody)
  res.send('hello world')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We have the rawBodySaver function that gets the buf parameter, which has the raw request body buffer.

Then we call toString on it with the encoding and assign that to the req.rawBody property.

Next, we set the verify property of options to rawBodySaver and then use options as the argument for bodyParser.json to set rawBodySaver as the function to run when the request body is being parsed.

Then in the POST / route, we can get the raw request body from the req.rawBody property.