Categories
React

How to Build a Simple Video Converter with Node.js

Videos are an incredibly popular medium for sharing information, but in the past, converting videos has always been a problem for people. With FFMPEG, this can now be solved easily.

What is FFMPEG

FFMPEG is a command line video and audio processing program that has many capabilities. It also supports multiple formats for video conversion. The capabilities of FFMPEG include: getting video and audio metadata, changing the resolution of videos, changing audio quality, compressing videos, removing audio from videos, remove video from audio, extract frames from video, change video aspect ratio, and much more.

Developers have done the hard work for us by creating a Node.js wrapper for FFMPEG. The package is called fluent-ffmpeg. It is located at https://github.com/fluent-ffmpeg/node-fluent-ffmpeg. This package allows us to run FFMPEG commands by calling the built-in functions.

In this article, we will build a video converter to change the source video into the format of the user’s choice. We will use the fluent-ffmpeg package for running the conversions. Because the jobs are long-running, we will also create a job queue so that it will run in the background.

We will use Express for the back end and React for the front end.

Back End

To get started, create a project directory and a backend folder inside it. In the backend folder, run npx express-generator to generate the files for the Express framework.

Next run npm i in the backend folder to download the packages in package.json.

Then we have to install our own packages. We need Babel to use import in our app. Also, we will use the Bull package for background jobs, CORS package for cross domain requests with the front end, fluent-ffmpeg for converting videos, Multer for file upload, Dotenv for managing environment variables, Sequelize for ORM, and SQLite3 for or database.

Run npm i @babel/cli @babel/core @babel/node @babel/preset-env bull cors dotenv fluent-ffmpeg multer sequelize sqlite3 to install all the packages.

Next add the .babelrc file to the backend folder:

{
    "presets": [
        "@babel/preset-env"
    ]
}

This enables the latest JavaScript features.

In the scripts section of package.json, replace the existing code with:

"start": "nodemon --exec npm run babel-node --  ./bin/www",
"babel-node": "babel-node"

This runs our program with Babel instead of the regular Node runtime.

Next, we create the Sequelize code by running npx sequelize-cli init which creates a config.json file.

Then in config.json, we replace the existing code with:

{
  "development": {
    "dialect": "sqlite",
    "storage": "development.db"
  },
  "test": {
    "dialect": "sqlite",
    "storage": "test.db"
  },
  "production": {
    "dialect": "sqlite",
    "storage": "production.db"
  }
}

Next we need to create our model and migration. We run:

npx sequelize-cli --name VideoConversion --attributes filePath:string,convertedFilePath:string,outputFormat:string,status:enum

To create the model and migration for the VideoConversions table.

In the newly created migration file, replace the existing code with:

"use strict";
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable("VideoConversions", {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      filePath: {
        type: Sequelize.STRING
      },
      convertedFilePath: {
        type: Sequelize.STRING
      },
      outputFormat: {
        type: Sequelize.STRING
      },
      status: {
        type: Sequelize.ENUM,
        values: ["pending", "done", "cancelled"],
        defaultValue: "pending"
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable("VideoConversions");
  }
};

This adds the constants for our enum.

In models/videoconversion.js, replace the existing code with:

"use strict";
module.exports = (sequelize, DataTypes) => {
  const VideoConversion = sequelize.define(
    "VideoConversion",
    {
      filePath: DataTypes.STRING,
      convertedFilePath: DataTypes.STRING,
      outputFormat: DataTypes.STRING,
      status: {
        type: DataTypes.ENUM("pending", "done", "cancelled"),
        defaultValue: "pending"
      }
    },
    {}
  );
  VideoConversion.associate = function(models) {
    // associations can be defined here
  };
  return VideoConversion;
};

This add the enum constants to the model.

Next run npx sequelize-init db:migrate to create our database.

Then create a files folder in the backend directory for storing the files.

Next we create our video processing job queue. Create a queues folder and inside it, create videoQueue.js file and add:

const Queue = require("bull");
const videoQueue = new Queue("video transcoding");
const models = require("../models");
var ffmpeg = require("fluent-ffmpeg");
const fs = require("fs");

const convertVideo = (path, format) => {
  const fileName = path.replace(/.[^/.]+$/, "");
  const convertedFilePath = `${fileName}_${+new Date()}.${format}`;
  return new Promise((resolve, reject) => {
    ffmpeg(`${__dirname}/../files/${path}`)
      .setFfmpegPath(process.env.FFMPEG_PATH)
      .setFfprobePath(process.env.FFPROBE_PATH)
      .toFormat(format)
      .on("start", commandLine => {
        console.log(`Spawned Ffmpeg with command: ${commandLine}`);
      })
      .on("error", (err, stdout, stderr) => {
        console.log(err, stdout, stderr);
        reject(err);
      })
      .on("end", (stdout, stderr) => {
        console.log(stdout, stderr);
        resolve({ convertedFilePath });
      })
      .saveToFile(`${__dirname}/../files/${convertedFilePath}`);
  });
};

videoQueue.process(async job => {
  const { id, path, outputFormat } = job.data;
  try {
    const conversions = await models.VideoConversion.findAll({ where: { id } });
    const conv = conversions[0];
    if (conv.status == "cancelled") {
      return Promise.resolve();
    }
    const pathObj = await convertVideo(path, outputFormat);
    const convertedFilePath = pathObj.convertedFilePath;
    const conversion = await models.VideoConversion.update(
      { convertedFilePath, status: "done" },
      {
        where: { id }
      }
    );
    Promise.resolve(conversion);
  } catch (error) {
    Promise.reject(error);
  }
});

export { videoQueue };

In the convertVideo function, we use fluent-ffmpeg to get the video file, then set the FFMPEG and FFProbe paths from the environment variables. Then we call toFormat to convert it to the format that the user wants. We add a log statement in the start, error, and end handlers to see the outputs and resolve our promise on the end event. When the conversion is complete, we save it to a new file.

videoQueue is a Bull queue that processes jobs in the background sequentially. Redis is required to run the queue, we will need a Ubuntu Linux installation. We run the following commands in Ubuntu to install and run Redis:

$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get install redis-server
$ redis-server

In the callback of the videoQueue.process function, we call the convertVideo function and update the path of the converted file and the status of the given job when the job is done.

Next we create our routes. Create a conversions.js file in the routes folder and add:

var express = require("express");
var router = express.Router();
const models = require("../models");
var multer = require("multer");
const fs = require("fs").promises;
const path = require("path");
import { videoQueue } from "../queues/videoQueue";
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "./files");
  },
  filename: (req, file, cb) => {
    cb(null, `${+new Date()}_${file.originalname}`);
  }
});
const upload = multer({ storage });

router.get("/", async (req, res, next) => {
  const conversions = await models.VideoConversion.findAll();
  res.json(conversions);
});

router.post("/", upload.single("video"), async (req, res, next) => {
  const data = { ...req.body, filePath: req.file.path };
  const conversion = await models.VideoConversion.create(data);
  res.json(conversion);
});

router.delete("/:id", async (req, res, next) => {
  const id = req.params.id;
  const conversions = await models.VideoConversion.findAll({ where: { id } });
  const conversion = conversions[0];
  try {
    await fs.unlink(`${__dirname}/../${conversion.filePath}`);
    if (conversion.convertedFilePath) {
      await fs.unlink(`${__dirname}/../files/${conversion.convertedFilePath}`);
    }
  } catch (error) {
  } finally {
    await models.VideoConversion.destroy({ where: { id } });
    res.json({});
  }
});

router.put("/cancel/:id", async (req, res, next) => {
  const id = req.params.id;
  const conversion = await models.VideoConversion.update(
    { status: "cancelled" },
    {
      where: { id }
    }
  );
  res.json(conversion);
});

router.get("/start/:id", async (req, res, next) => {
  const id = req.params.id;
  const conversions = await models.VideoConversion.findAll({ where: { id } });
  const conversion = conversions[0];
  const outputFormat = conversion.outputFormat;
  const filePath = path.basename(conversion.filePath);
  await videoQueue.add({ id, path: filePath, outputFormat });
  res.json({});
});

module.exports = router;

In the POST / route, we accept the file upload with the Multer package. We add the job and save the file to the files folder that we created before. We save it with the file’s original name in the filename function in the object we passed into the diskStorage function and specified the file be saved in the files folder in the destination function.

The GET route / route gets the jobs added. DELETE / deletes the job with the given ID along with the original and converted file of the job. PUT /cancel/:id route sets status to cancelled .

The GET /start/:id route adds the job with the given ID to the queue we created earlier.

In app.js, we replace the existing code with:

require("dotenv").config();
var createError = require("http-errors");
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var cors = require("cors");

var indexRouter = require("./routes/index");
var conversionsRouter = require("./routes/conversions");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "files")));
app.use(cors());

app.use("/", indexRouter);
app.use("/conversions", conversionsRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get("env") === "development" ? err : {};

// render the error page
  res.status(err.status || 500);
  res.render("error");
});

module.exports = app;

This adds the CORS add-on to enable cross domain communication, exposes the files folder to the public, and exposes the conversions routes we created earlier to the public.

To add the environment variables, create an .env file in the backend folder and add:

FFMPEG_PATH='c:ffmpegbinffmpeg.exe'
FFPROBE_PATH='c:ffmpegbinffprobe.exe'

Front End

With back end done, we can move on to the front end. In the project’s root folder, run npx create-react-app frontend to create the front end files.

Next we install some packages. We need Axios for making HTTP requests, Formik for form value handling, MobX for state management, React Router for routing URLs to our pages, and Bootstrap for styling.

Run npm i axios bootstrap formik mobx mobx-react react-bootstrap react-router-dom to install the packages.

Next we replace the existing code in App.js with:

import React from "react";
import { Router, Route } from "react-router-dom";
import "./App.css";
import { createBrowserHistory as createHistory } from "history";
import HomePage from "./HomePage";
import { ConversionsStore } from "./store";
import TopBar from "./TopBar";
const conversionsStore = new ConversionsStore();
const history = createHistory();

function App() {
  return (
    <div className="App">
      <TopBar />
      <Router history={history}>
        <Route
          path="/"
          exact
          component={props => (
            <HomePage {...props} conversionsStore={conversionsStore} />
          )}
        />
      </Router>
    </div>
  );
}

export default App;

We add the top bar and the routes in this file.

In App.css, we replace the existing code with:

.page {
  padding: 20px;
}

.button {
  margin-right: 10px;
}

Next create HomePage.js in the src folder and add:

import React from "react";
import Table from "react-bootstrap/Table";
import Button from "react-bootstrap/Button";
import ButtonToolbar from "react-bootstrap/ButtonToolbar";
import { observer } from "mobx-react";
import {
  getJobs,
  addJob,
  deleteJob,
  cancel,
  startJob,
  APIURL
} from "./request";
import { Formik } from "formik";
import Form from "react-bootstrap/Form";
import Col from "react-bootstrap/Col";

function HomePage({ conversionsStore }) {
  const fileRef = React.createRef();
  const [file, setFile] = React.useState(null);
  const [fileName, setFileName] = React.useState("");
  const [initialized, setInitialized] = React.useState(false);

  const onChange = event => {
    setFile(event.target.files[0]);
    setFileName(event.target.files[0].name);
  };

  const openFileDialog = () => {
    fileRef.current.click();
  };

  const handleSubmit = async evt => {
    if (!file) {
      return;
    }
    let bodyFormData = new FormData();
    bodyFormData.set("outputFormat", evt.outputFormat);
    bodyFormData.append("video", file);
    await addJob(bodyFormData);
    getConversionJobs();
  };

  const getConversionJobs = async () => {
    const response = await getJobs();
    conversionsStore.setConversions(response.data);
  };

  const deleteConversionJob = async id => {
    await deleteJob(id);
    getConversionJobs();
  };

  const cancelConversionJob = async id => {
    await cancel(id);
    getConversionJobs();
  };

  const startConversionJob = async id => {
    await startJob(id);
    getConversionJobs();
  };

  React.useEffect(() => {
    if (!initialized) {
      getConversionJobs();
      setInitialized(true);
    }
  });

  return (
    <div className="page">
      <h1 className="text-center">Convert Video</h1>
      <Formik onSubmit={handleSubmit} initialValues={{ outputFormat: "mp4" }}>
        {({
          handleSubmit,
          handleChange,
          handleBlur,
          values,
          touched,
          isInvalid,
          errors
        }) => (
          <Form noValidate onSubmit={handleSubmit}>
            <Form.Row>
              <Form.Group
                as={Col}
                md="12"
                controlId="outputFormat"
                defaultValue="mp4"
              >
                <Form.Label>Output Format</Form.Label>
                <Form.Control
                  as="select"
                  value={values.outputFormat || "mp4"}
                  onChange={handleChange}
                  isInvalid={touched.outputFormat && errors.outputFormat}
                >
                  <option value="mov">mov</option>
                  <option value="webm">webm</option>
                  <option value="mp4">mp4</option>
                  <option value="mpeg">mpeg</option>
                  <option value="3gp">3gp</option>
                </Form.Control>
                <Form.Control.Feedback type="invalid">
                  {errors.outputFormat}
                </Form.Control.Feedback>
              </Form.Group>
            </Form.Row>

            <Form.Row>
              <Form.Group as={Col} md="12" controlId="video">
                <input
                  type="file"
                  style={{ display: "none" }}
                  ref={fileRef}
                  onChange={onChange}
                  name="video"
                />
                <ButtonToolbar>
                  <Button
                    className="button"
                    onClick={openFileDialog}
                    type="button"
                  >
                    Upload
                  </Button>
                  <span>{fileName}</span>
                </ButtonToolbar>
              </Form.Group>
            </Form.Row>

            <Button type="submit">Add Job</Button>
          </Form>
        )}
      </Formik>

      <br />
      <Table>
        <thead>
          <tr>
            <th>File Name</th>
            <th>Converted File</th>
            <th>Output Format</th>
            <th>Status</th>
            <th>Start</th>
            <th>Cancel</th>
            <th>Delete</th>
          </tr>
        </thead>
        <tbody>
          {conversionsStore.conversions.map(c => {
            return (
              <tr>
                <td>{c.filePath}</td>
                <td>{c.status}</td>
                <td>{c.outputFormat}</td>
                <td>
                  {c.convertedFilePath ? (
                    <a href={`${APIURL}/${c.convertedFilePath}`}>Open</a>
                  ) : (
                    "Not Available"
                  )}
                </td>
                <td>
                  <Button
                    className="button"
                    type="button"
                    onClick={startConversionJob.bind(this, c.id)}
                  >
                    Start
                  </Button>
                </td>
                <td>
                  <Button
                    className="button"
                    type="button"
                    onClick={cancelConversionJob.bind(this, c.id)}
                  >
                    Cancel
                  </Button>
                </td>
                <td>
                  <Button
                    className="button"
                    type="button"
                    onClick={deleteConversionJob.bind(this, c.id)}
                  >
                    Delete
                  </Button>
                </td>
              </tr>
            );
          })}
        </tbody>
      </Table>
    </div>
  );
}

export default observer(HomePage);

This is the home page of our app. We have a dropdown for selecting the format of the file, an upload button for select the file for conversion, and a table for displaying the video conversion jobs with the status and file names of the source and converted files.

We also have buttons to start, cancel, and delete each job.

To add file upload, we have a hidden file input and in the onChange handler of the file input. The Upload button’s onClick handler will click the file input to open the upload file dialog.

We get latest jobs by calling getConversionJobs when we first load the page, and also when we start, cancel, and delete jobs. The job data is stored in the MobX store that we will create later. We wrap observer in our HomePage in the last line to always get the latest values from the store.

Next create request.js and the src folder and add:

const axios = require("axios");
export const APIURL = "http://localhost:3000";

export const getJobs = () => axios.get(`${APIURL}/conversions`);

export const addJob = data =>
  axios({
    method: "post",
    url: `${APIURL}/conversions`,
    data,
    config: { headers: { "Content-Type": "multipart/form-data" } }
  });

export const cancel = id => axios.put(`${APIURL}/conversions/cancel/${id}`, {});

export const deleteJob = id =>
  axios.delete(`${APIURL}/conversions/${id}`);

export const startJob = id => axios.get(`${APIURL}/conversions/start/${id}`);

The HTTP requests that we make to the back end are all here. They were used on the HomePage .

Next create the MobX store by creating the store.js file in the src folder. In there add:

import { observable, action, decorate } from "mobx";

class ConversionsStore {
  conversions = [];

  setConversions(conversions) {
    this.conversions = conversions;
  }
}

ConversionsStore = decorate(ConversionsStore, {
  conversions: observable,
  setConversions: action
});

export { ConversionsStore };

This is a simple store that persists the contacts, and the conversions array is where we store the contacts for the whole app. The setConversions function lets us set contacts from any component where we pass in this store object to.

Next create TopBar.js in the src folder and add:

import React from "react";
import Navbar from "react-bootstrap/Navbar";
import Nav from "react-bootstrap/Nav";

function TopBar() {
  return (
    <Navbar bg="primary" expand="lg" variant="dark">
      <Navbar.Brand href="#home">Video Converter</Navbar.Brand>
      <Navbar.Toggle aria-controls="basic-navbar-nav" />
      <Navbar.Collapse id="basic-navbar-nav">
        <Nav className="mr-auto">
          <Nav.Link href="/">Home</Nav.Link>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  );
}

export default TopBar;

This contains the React Bootstrap Navbar to show a top bar with a link to the home page and the name of the app.

In index.html, we replace the existing code with:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="logo192.png" />
    <!--
      manifest.json provides metadata used when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>Video Converter</title>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
      integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

This adds the Bootstrap CSS and changes the title.

After writing all that code, we can run our app. Before running anything, install nodemon by running npm i -g nodemon so that we don’t have to restart the back end ourselves when files change.

Then run back end by running npm start in the backend folder and npm start in the frontend folder, then choose ‘yes’ if you’re asked to run it from a different port.

Categories
JavaScript

Top Frameworks and Libraries to Make Developing Web Apps Easier

With plain JavaScript we can do a lot of things. However, there’s no set structure or if we write plain JavaScript code, so developers need a lot of discipline to structure their code properly. This takes a lot of effort and so it wastes a lot of developer’s time enforcing structure of every part of the code.

Manipulating the DOM is also very fragile because in today’s web apps, there are way too many things going on which can change the DOM. This means that elements appear and disappear in indeterminate amount of times. This create issues since we might be trying to manipulate DOM elements that aren’t there yet. Or multiple pieces of code might try to modify the same element at the same time.

It’s just too difficult to troubleshoot those issues and get your code working correctly. This means that a lot of time on these little issues, which takes away developer’s time that can be used to develop features. This is where frameworks come in to save the day.

Frameworks provide structure which allows teams of developers to develop complex web apps in a structured way. Most frameworks enforce their own conventions so structures can be enforced if multiple developers develop the same application. DOM manipulation is abstracted away in frameworks so that developers do not have to worry about that unless they develop features that need direct DOM manipulation like animations.

Libraries are small pieces of code that we can include in our app’s code to extend the functionality of our apps. Libraries make add functionality easier and some also provide shortcuts that does the equivalent of what’s available in plain JavaScript but better. There are also libraries that are made for specific frameworks to enhance their functionality.

Vue.js

Vue.js is a component based front end JavaScript framework that lets developers create high quality maintainable web apps in an easy way. The framework lets developers divide their app into Vue.js components, which are self contained parts that when put together, we get a full web app. Components are made to be nested within each other. Each component has a template for rendering the data, a script section for the logic, and a styles section for the CSS styles. Component support data binding between the template and script sections which means that changes from the template section is automatically reflected in the script section and vice versa. Each component has its own life cycle and has function to handle those life cycle events. Parent components can pass data into child components and child component can emit events to pass components into the parent.

With Vue.js, DOM manipulation is done in the background by getting the difference between the browser DOM and the virtual DOM tree it creates and make the changes from the virtual DOM to the actual DOM.

Also there’s a built in URL router called the Vue Router that lets developers map specific URLs into the pages of their apps. For centralize state management it uses the Vuex flux library which lets us use the flux architecture to store the app’s state centrally. Flux architecture basically means that data are set in a central data store and then components that need the data always get the latest data from the store by observing the values from the store.

New apps usually use the Vue CLI to create the project and select what to include.

Other feature it supports out of the box includes testing, CSS preprocessors like SCSS and SASS to make writing complex CSS easier, and building to web components or progressive web apps, and other advanced features. It can also be added incrementally to legacy web apps by using script tags. The Vue.js framework and libraries made for Vue.js all support this. So it’s a great choice for upgrading the functionality of legacy web apps.

There’s large ecosystem of libraries that we can use with Vue.js applications including component libraries, helper modules geolocation and webRTC modules and many others.

Angular

Like Vue.js, Angular is a component based framework. It’s made by Google. Most of the things that’s part of the Vue.js feature set is also in Angular, except the state management part. By default, Angular applications are written in TypeScript he framework lets developers divide their app into Angular components, which are self contained parts that when put together, we get a full web app. Components are made to be nested within each other. Each component has a template file for rendering the data, a TypeScript file for the logic, and a styles file for styling, which can be CSS, SASS or SCSS. Also, there’s a test file to add your unit tests for each component. Component support data binding between the template and script sections which means that changes from the template section is automatically reflected in the TypeScript file and vice versa. Each component has its own life cycle and has function to handle those life cycle events. Parent components can pass data into child components and child component can emit events to pass components into the parent.

Many parts of the library uses reactive programming, which means that parts of the app watches for data changes and does something when it changes. This is done mainly with observables.

One unique feature of Angular is that it includes dependency injection so that we don’t have to worry about resolving the dependencies of Angular libraries ourselves, which saves a lot of headaches since most web apps probably lots of dependencies.

Angular apps are divided into modules, which we can combine into one to make one whole app. Each module include the libraries that are needed to be used by that module.

With Angular, DOM manipulation is done in the background by getting the difference between the browser DOM and the virtual DOM tree it creates and make the changes from the virtual DOM to the actual DOM.

Also there’s a built in URL router called the Angular Router that lets developers map specific URLs into the pages of their apps.

Other feature it supports out of the box includes building to web components or progressive web apps, and other advanced features. There’s large ecosystem of libraries that we can use with React applications including component libraries, helper modules like NgRx store for state management many others.

React

React is a component based library that we can use to make dynamic web apps. It uses the JSX syntax for writing JavaScript which looks like HTML, except that you can mix it with JavaScript directly. Each component has its own life cycle and has function to handle those life cycle events. It also provides nesting for components and also allow for higher order components, which are components that returns component. There are 2 kinds of components in React. One is class based components, which are written as a class, with a render method at the end to render the HTML. The other is function components which returns the JSX directly and rendered into HTML. Originally function components cannot have dynamic logic, but now that React has hooks, function components can also have logic code in it.

With React, DOM manipulation is done in the background by getting the difference between the browser DOM and the virtual DOM tree it creates and make the changes from the virtual DOM to the actual DOM.

It does not include anything other than a view library to render JavaScript into HTML, so if we want to build a full single page application, we need to add other libraries like React Router and a state management like Redux. There’s large ecosystem of libraries that we can use with React applications including component libraries, helper modules like React Router and Redux and many others.

Lodash

Lodash is a library which contains many handy methods for manipulating data. Examples include array methods like flatten to squash a nested array into an ordinary array. There’s also a flattenDeep to flatten all levels of a nested array into a flat array. Other functions include:

  • findIndex — find the index of a given object
  • findLastIndex — find the last index of a given object
  • pull — removes the first given item from the array
  • pullAll — remove all the given item from the array
  • reverse — reverse an array
  • sortedIndex — get the index to insert the given item so that the array stays sorted
  • get — function used to traverse an object to get the item with the given property and return null if it can’t traverse the object to get the item or if it’s null or undefined

There are many more functions that aren’t yet available in plain JavaScript, even though some like find and findIndex did make it into JavaScript’s standard library, so Lodash is still useful.

Moment.js

Manipulating time and date in JavaScript is painful. Even with the functions available with Date objects, there are plenty of chances of bugs and errors. Also, there are no functions for formatting times and dates which is a big problem. To solve this, we use moment.js. This is the best library available for dealing with time.

There were issues with time zones with YYYY-MM-DD dates being parsed into UTC time as opposed to local time. Which creates bugs for developers who aren’t aware of this problem. See https://stackoverflow.com/questions/29174810/javascript-date-timezone-issue

Also there are difference in support for parts of Dates in different browsers. (See https://stackoverflow.com/questions/11253351/javascript-date-object-issue-in-safari-and-ie)

It is also hard to add and subtract timestamps with built in Date functions. There is no way to do this without writing a lot of code and doing a lot of checks. Also, there is no way to compare 2 times.

Formatting dates is also not available without writing your own code for using third party libraries.

Moment.js solves all of these issues by providing built in functions to do all these common operations. It provides functions for parsing and formatting dates.

The momentconstructor is where you can pass in a date string, and a moment object will be created. For example, you can pass in:

moment('2019-08-04')

and you will get back a moment which you can compare with other moment objects, and add or subtract by different time spans.

If you do not passing in anything to the moment constructor, you get the current date and time.

It also takes a second argument. If you want to make sure a date is parsed as a YYYY-MM-DD date, then write moment(‘2019–08–04’, 'YYYY-MM-DD') . If you don’t know the format of your date or time, then you can pass in an array of possible formats and Moment will pick the right one:

moment('2019–08–04', ['YYYY-MM-DD', 'DD-MM-YYYY']);

After you create a Moment object, then you can do many things like formatting dates:

const a = moment('2019–08–04', 'YYYY-MM-DD').format('MMMM Do YYYY, h:mm:ss a');
console.log(a);// August 4th 2019, 12:00:00 am

const b = moment('2019–08–04', 'YYYY-MM-DD').format('dddd');
console.log(b);// Sunday

const c = moment('2019–08–04', 'YYYY-MM-DD').format("MMM Do YY");
console.log(c);// Aug 4th 19

const d = moment('2019–08–04', 'YYYY-MM-DD').format('YYYY [escaped] YYYY');
console.log(d);// 2019 escaped 2019

const e = moment('2019–08–04', 'YYYY-MM-DD').format();
console.log(e);// 2019-08-04T00:00:00-07:00

From the above examples, we see that we can format dates in pretty much any way we want.

We can also tell what time span a date is relative to another date by writing:

const augDate = moment('2019–08–04', 'YYYY-MM-DD');
const sepDate = moment('2019–09–04', 'YYYY-MM-DD');console.log(augDate.from(sepDate)); // a month ago

We can also add or subtract Moment dates:

const augDate = moment('2019–08–04', 'YYYY-MM-DD');
const sepDate = moment('2019–09–04', 'YYYY-MM-DD');console.log(augDate.add(10, 'days').calendar()); // 08/14/2019
console.log(augDate.subtract(10, 'days').calendar()); // 07/25/2019

It is easy to compare 2 dates

moment('2010-01-01').isSame('2010-01-01', 'month'); // true
moment('2010-01-01').isSame('2010-05-01', 'day');   // false, different month
moment('2008-01-01').isSame('2011-01-01', 'month'); // false, different year

You can also check if a date is has Daylight Saving Time in effect or not:

const augDate = moment('2019–08–04', 'YYYY-MM-DD');
const decDate = moment('2019–12–04', 'YYYY-MM-DD');
console.log(augDate.isDST()) // true
console.log(decDate.isDST()) // false

And you can convert back to JavaScript date any time by calling the toDate() function on a Moment object.

As we can see. There’re lots of things that Moment.js can do that can’t be done in plain JavaScript, so we need this library badly.

All in all, developing front end JavaScript web apps feels almost like magic with all these libraries and frameworks. It makes development a lot easier if you’re working alone and in teams. There’s no way to live without all these modern day libraries and frameworks. A lot of these things that frameworks and libraries do aren’t possible with plain JavaScript.

Categories
JavaScript Answers

How to Get a Key in a JavaScript Map by its Value?

To get a key in a JavaScript map by its value, we can use the spread operator to spread the entries into an array.

Then we can use the filter method to return an array with the entries with the given value.

For instance, we can write:

const people = new Map();
people.set('1', 'john');
people.set('2', 'jasmin');
people.set('3', 'foo');

const keys = [...people.entries()]
  .filter(([, v]) => v === 'john')
  .map(([k]) => k);

console.log(keys);

We create the people map with a few entries.

And we want to find the key for the entry with 'john' as its value.

To do this, we call people.entries() to return an iterator with the key-value pair arrays from the map.

Then we spread the iterator entries into an array with the spread operator.

Next, we call filter with a callback that destructures the v map value from the parameter.

And we return the entries where value v is 'john'.

Finally, we call map to map the k keys from the map and return them in the returned array.

Therefore, keys is ["1"] as we can see from the console log.

Categories
JavaScript Answers

How to Unbind Event Handlers to Bind Them Again Later with jQuery?

To unbind event handlers to bind them again later with jQuery, we can use the _data to get the event bindinds.

Then we can get the click event binding with the click property.

For instance, if we have:

<a id="test">test</a>

Then we write:

$(document).ready(() => {
  $('#test').click((e) => {
    const events = $._data($('#test')[0], 'events');
    $('#test').unbind('click', events.click[0]);
  });
});

to add the click event listeners with the click method.

In the click event handler callback, we get the bindings with:

$._data($('#test')[0], 'events')

and assign it to events.

Then we unbind the click event handler with:

$('#test').unbind('click', events.click[0]);

Then when we want to bind to the click event, we can use the events to bind the event again.

Categories
JavaScript Answers

How to Get the Last Value Inserted into a JavaScript Set?

To get the last value inserted into a JavaScript set, we can spread the set entries into an array.

Then we can call the pop method on the returned array to return the last entry inserted into the set.

For instance, we can write:

const a = new Set([1, 2, 3]);
a.add(10);
const lastValue = [...a].pop();
console.log(lastValue)

We create a new set with the Set constructor.

Then we call add to add a new entry into the set.

Next, we spread a set into an array and then call pop to return the last element from the set and remove that entry from the array.

The returned item is assigned to lastValue.

Therefore, from the console log, we see that lastValue is 10.