Categories
JavaScript Answers

How to generate an MD5 file hash in JavaScript and Node.js?

To generate an MD5 file hash in JavaScript and Node.js, we use CryptoJS.

For instance, we write

import MD5 from "crypto-js/md5";
console.log(MD5("Message").toString());

to call the MD5 function to encrypt the 'Message' message.

We return the hash as a string with toString.

Categories
JavaScript Answers

How to uninstall global package with npm with JavaScript?

To uninstall global package with npm with JavaScript, we run npm uninstall with the -g flag.

For instance, we run

npm uninstall -g webpack

to uninstall the global version of webpack.

Categories
JavaScript Answers

How to add custom certificate authority (CA) to Node.js?

To add custom certificate authority (CA) to Node.js, we call the options.ca.push method.

For instance, we write

const trustedCa = [
  "/etc/pki/tls/certs/ca-bundle.crt",
  "/path/to/custom/cert.crt",
];

https.globalAgent.options.ca = [];
for (const ca of trustedCa) {
  https.globalAgent.options.ca.push(fs.readFileSync(ca));
}

to loop through each trusrtedCa path with a for-of loop.

In it, we call https.globalAgent.options.ca.push with the file read from readFileSync to add the certificate file into the array with push.

Categories
JavaScript Answers

How to create Mongoose schema with array of Object IDs with JavaScript?

To create Mongoose schema with array of Object IDs with JavaScript, we use an array.

For instance, we write

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  name: {
    first: { type: String, required: true, trim: true },
    last: { type: String, required: true, trim: true },
  },
  phone: Number,
  lists: [listSchema],
  friends: [{ type: ObjectId, ref: "User" }],
  accessToken: { type: String },
});
exports.User = mongoose.model("User", userSchema);

to create the userSchema that has the friends field set to an array of object IDs.

We do that by setting it an array with an object with type set toi ObjectId.

ref is the collection that the IDs are referencing.

Categories
JavaScript Answers

How to call an asynchronous function within map with JavaScript?

To call an asynchronous function within map with JavaScript, we use the for-of loop.

For instance, we write

const promises = teachers.map(async (m) => {
  return await request.get("...");
});

for (let val of promises) {
  //....
}

to call teachers.map with a callback to return an array of promises.

Then we use the for-of loop to loop through each promise in the promises array and run them.