Categories
JavaScript Answers

How to get image from web and encode with base64 with Node.js?

To get image from web and encode with base64 with Node.js, we call the axios.get method.

For instance, we write

const axios = require("axios");
//...
const image = await axios.get(url, { responseType: "arraybuffer" });
const raw = Buffer.from(image.data).toString("base64");
const base64Image = "data:" + image.headers["content-type"] + ";base64," + raw;

to call axios.get to get the image from url with a get request.

We get the response as an arraybuffer with { responseType: "arraybuffer" }.

Then we call Buffer.from to convert the arraybuffer to a buffer.

And we call toString with 'base64' to convert it to a base64 string.

Then we put the content type string before the string.

Categories
JavaScript Answers

How to output ‘id’ instead of ‘_id’ with Node.js MongoDB?

To output ‘id’ instead of ‘_id’ with Node.js MongoDB, we call set to modify the toJSON method.

For instance, we write

Schema.set("toJSON", {
  virtuals: true,
});

to call set with an object that sets virtuals to true to change _id to id and return it.

Categories
JavaScript Answers

How to fix cannot enqueue Handshake after invoking quit with Node.js MySQL?

To fix cannot enqueue Handshake after invoking quit with Node.js MySQL, we create a connection pool.

For instance, we write

const mysql = require("mysql");
const pool = mysql.createPool({
  //...
});

pool.getConnection((err, connection) => {
  connection.query("...", (err, rows) => {
    connection.release();
  });
});

to call createPool tro create a connection pool.

Then we call getConnection to get the database connection.

And we call query to make the query with the connection in the callback.

Once we’re done, we call release to release the connection.

Categories
JavaScript Answers

How to import a JavaScript package from a CDN or script tag in React?

To import a JavaScript package from a CDN or script tag in React, we get the library from window.

For instance, we write

<script src="https://cdn.dwolla.com/1/dwolla.js"></script>

to add the dwolla library with a script element.

Then we get the dwolla library with

const dwolla = window.dwolla;
Categories
JavaScript Answers

How to replace callbacks with promises in Node.js?

To replace callbacks with promises in Node.js, we use the util.promisify method.

For instance, we write

const util = require("util");

const connectAsync = util.promisify(connection.connectAsync);
const queryAsync = util.promisify(connection.queryAsync);

exports.getUsersAsync = async () => {
  await connectAsync();
  return queryAsync("SELECT * FROM Users");
};

to call util.promisify with the connectAsync and queryAsync methods to convert them to functions that return promises.

And then we call connectAsync to return a promise and use await to run the promise.