Categories
JavaScript Answers

How to hash password with Mongoose?

Sometimes, we want to hash password with Mongoose.

In this article, we’ll look at how to hash password with Mongoose.

How to hash password with Mongoose?

To hash password with Mongoose, we can use bcrypt.

For instance, we write

const mongoose = require("mongoose");
const { Schema } = mongoose;
const bcrypt = require("bcrypt");
const SALT_WORK_FACTOR = 10;

const UserSchema = new Schema({
  username: { type: String, required: true, index: { unique: true } },
  password: { type: String, required: true },
});

UserSchema.pre("save", function (next) {
  if (!user.isModified("password")) {
    return next();
  }
  bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
    if (err) return next(err);
    bcrypt.hash(this.password, salt, (err, hash) => {
      if (err) return next(err);
      this.password = hash;
      next();
    });
  });
});

UserSchema.methods.comparePassword = (candidatePassword, cb) => {
  bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
    if (err) {
      return cb(err);
    }
    cb(null, isMatch);
  });
};

module.exports = mongoose.model("User", UserSchema);

to create the User schema with the password field.

When we save the User entry, we call bcrypt.getSalt to generate the salt.

In the genSalt callback, we call bcrypt.hash to hash the password with the salt created.

And then we set this.password to hash and call next to save.

Then we create the comparePassword method by setting UserSchema.methods.comparePassword to a function that calls bcrypt.compare with the candidatePssword and this.password which is current password saved.

We call the cb callback that we call comparePassword with in the function and get whether both passwords match with isMatch.

Then we use it by writing

const testUser = new User({
  username: "abc",
  password: "password123",
});

testUser.save((err) => {
  if (err) throw err;
});

User.findOne({ username: "abc" }, (err, user) => {
  if (err) throw err;

  user.comparePassword("password123", (err, isMatch) => {
    if (err) throw err;
    console.log("password123:", isMatch);
  });

  user.comparePassword("abc", (err, isMatch) => {
    if (err) throw err;
    console.log("abc:", isMatch);
  });
});

to create the testUser User.

And then we call findOneto find the user withusernameset to‘abc’`.

In the findOne callback, we call comparePassword to compare valid and invalid passwords respectively and get whether they match the saved password with isMatch.

Conclusion

To hash password with Mongoose, we can use bcrypt.

Categories
JavaScript Answers

How to set max viewport in Puppeteer?

Sometimes, we want to set max viewport in Puppeteer.

In this article, we’ll look at how to set max viewport in Puppeteer.

How to set max viewport in Puppeteer?

To set max viewport in Puppeteer, we set the defaultViewport option to null.

For instance, we write

const browser = await puppeteer.launch({ defaultViewport: null });

to call puppeteer.luanch with an object that has defaultViewport set to null.

This will make Puppeteer launch with the max viewport resolution instead of 800×600.

Conclusion

To set max viewport in Puppeteer, we set the defaultViewport option to null.

Categories
JavaScript Answers

How to parse XLSX and create JSON with Node.js?

Sometimes, we want to parse XLSX and create JSON with Node.js.

In this article, we’ll look at how to parse XLSX and create JSON with Node.js.

How to parse XLSX and create JSON with Node.js?

To parse XLSX and create JSON with Node.js, we can use the xlsx package.

To install it, we run

npm i xlsx

Then we use it by writing

const XLSX = require("xlsx");
const workbook = XLSX.readFile("Master.xlsx");
const { SheetNames: sheetNames } = workbook;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheetNames[0]]));

to call XLSX.readFile to read the XLSX file from the path in the argument/

Then we get the sheetNames from the workbook object.

Next, we call XLSX.utils.sheet_to_json with the first sheet which we get from workbook.Sheets[sheetNames[0]] return the JSON data converted from the worksheet.

Conclusion

To parse XLSX and create JSON with Node.js, we can use the xlsx package.

Categories
JavaScript Answers

How to get a JSON via HTTP request in Node.js?

Sometimes, we want to get a JSON via HTTP request in Node.js.

In this article, we’ll look at how to get a JSON via HTTP request in Node.js.

How to get a JSON via HTTP request in Node.js?

To get a JSON via HTTP request in Node.js, we can call request with json set to true.

For instance, we write

const options = {
  hostname: "127.0.0.1",
  port: app.get("port"),
  path: "/users",
  method: "GET",
  json: true,
};
request(options, (error, response, body) => {
  console.log(body);
});

to call request with json set to true in the options object to return a JSON response.

Then we get the parsed JSON response body from the body parameter in the callback.

Conclusion

To get a JSON via HTTP request in Node.js, we can call request with json set to true.

Categories
JavaScript Answers

How to scale socket.IO to multiple Node.js processes using cluster?

Sometimes, we want to scale socket.IO to multiple Node.js processes using cluster.

In this article, we’ll look at how to scale socket.IO to multiple Node.js processes using cluster.

How to scale socket.IO to multiple Node.js processes using cluster?

To scale socket.IO to multiple Node.js processes using cluster, we can use cluster to create workers processes.

For instance, we write

const cluster = require("cluster");
const os = require("os");

if (cluster.isMaster) {
  const server = require("http").createServer();
  const io = require("socket.io").listen(server);

  const RedisStore = require("socket.io/lib/stores/redis");
  const redis = require("socket.io/node_modules/redis");

  io.set(
    "store",
    new RedisStore({
      redisPub: redis.createClient(),
      redisSub: redis.createClient(),
      redisClient: redis.createClient(),
    })
  );

  setInterval(function () {
    io.sockets.emit("data", "payload");
  }, 1000);

  for (let i = 0; i < os.cpus().length; i++) {
    cluster.fork();
  }

  cluster.on("exit", (worker, code, signal) => {
    console.log("worker " + worker.process.pid + " died");
  });
}

if (cluster.isWorker) {
  const express = require("express");
  const app = express();

  const http = require("http");
  const server = http.createServer(app);
  const io = require("socket.io").listen(server);

  const RedisStore = require("socket.io/lib/stores/redis");
  const redis = require("socket.io/node_modules/redis");

  io.set(
    "store",
    new RedisStore({
      redisPub: redis.createClient(),
      redisSub: redis.createClient(),
      redisClient: redis.createClient(),
    })
  );

  io.sockets.on("connection", (socket) => {
    socket.emit("data", "connected to worker: " + cluster.worker.id);
  });

  app.listen(80);
}

to create a server on the master with

const server = require('http').createServer();

Then we call cluster.fork(); to create worker processes.

Then we create express servers on the workers with

const server = http.createServer(app);

We use Redis to do the caching with both the cluster master and worker.

Conclusion

To scale socket.IO to multiple Node.js processes using cluster, we can use cluster to create workers processes.