Skip to main content

Posts

Showing posts with the label javascript

How To Use Protocol Buffer in Javascript

We have understood a few advantages of protocol buffer like what I've explained in my other post . Now, let's look at how we can implement it in our code. The "transpiler" tool, named protoc , supports the generation of a helper class for managing the object instance in a variety of programming languages. In this post, we use Javascript as an example and run in a Linux environment. Preparation Before we develop our code, we should install protoc for generating the helper class. Download protoc binary from the release page . Extract the content and store the directories  ( bin  and  includes ) in /usr/local  directory so that the executable binary can be accessed directly. Run protoc --help to check its manual. Install a required dependency globally to enable protoc  to generate the Javascript files by running: npm i -g protoc-gen-js . Create a proto file First, we should create an ...

Invisible Closure Scope in Javascript

When we are maintaining variables in our Javascript code, we must already know about the scope that determines the visibility of variables. There are three types of scope which are block, function, and global scope. A variable defined inside a function is not visible (accessible) from outside the function. But, the variable is visible to any blocks or functions inside the function. When a function is created, it has access to variables in the parent scope and its own scope, and it is known as closure scope. For example, if we create a function (child) inside another function (parent), in the creation time the child function will also have access to variables declared in its parent. Another way to think of closure is that every function in JavaScript has a hidden property called "Scope", which contains a reference to the environment where the function was created. The environment consists of the local variables, parameters, and arguments that were available to the...

Detecting Main Module in ESM Package

ESM package works in a different fashion from CJS. ESM package imports required modules asynchronously and have no support for several functions related to system files and directories. ESM follows Javascript cores that are implemented in the browser. There is no such entity like __dirname , __filename , require() , and so on. If we want to detect whether a module is a main module that is being run in CJS, we can compare the value of require.module and module . If it is the same, the module is being run as the main module. Meanwhile, for a module in the ESM package, we can use the following approach. Get the value of process.argv[1] that contains information of the main file that is being called by Node. Get the value of import.meta.url that contains information of the module's location that is being accessed. Transform the information to have a similar format, then compare it. For example, we have a module in an ESM package, named module1.js . import { r...

Prototypal Inheritance in Javascript

Some programming languages support object-oriented approaches natively by providing a feature to create an object instance based on a class definition. Meanwhile, in Javascript, we know there is  class syntax, but it is just a kind of syntactic sugar that allows us to instantiate an object that can inherit some traits from another object or class definition in a similar fashion to other programming languages. In Javascript, a class is just a function with a  prototype property that maintain traits that can be passed down to other object instance. There are several ways to allow property inheritance in Javascript. Functional In this way, we utilize the Object.create() method built in Javascript. The steps are: Create an object as the prototype provider. Pass the prototype provider to the Object.create() method along with additional properties declaration if needed. For example, const provider = { sum: (a, b) => a + b }; const obj = Object.create( ...

Double Invoking In React Application with Strict Mode Enabled

When we use create-react-app to generate our application source code, we will be provided with a base code that enables  React.StrictMode by default. This wrapper component doesn't render an HTML element but it performs useful functionality to verify that our application is safe for production. It checks for legacy or deprecated React functions or APIs, unexpected side-effects, and unsafe lifecycle. We can read the details about those functionalities on its documentation page . To help us spot side-effects, React will double-invoking several functions in our application such as render , constructor , functions passed in useMemo or useReducer , and so on. By double-invoking such functions, we can detect if unexpected results will show up. But, this process will be initiated only in development mode. When we ship our application in a production environment with Strict Mode enabled, double-invoking will never happen. This is why when we render a component that contains useEffect ...

Managing MongoDB Records Using NestJS and Mongoose

NestJS is a framework for developing Node.js-based applications. It provides an additional abstraction layer on top of Express or other HTTP handlers and gives developers a stable foundation to build applications with structured procedures. Meanwhile, Mongoose is a schema modeling helper based on Node.js for MongoDB. There are several main steps to be performed for allowing our program to handle MongoDB records. First, we need to add the dependencies which are @nestjs/mongoose , mongoose , and @types/mongoose . Then, we need to define the connection configuration on the application module decorator. import { MongooseModule } from '@nestjs/mongoose'; @Module({ imports: [ MongooseModule.forRoot('mongodb://localhost:27017/mydb'), ], controllers: [AppController], providers: [AppService], }) Next, we create the schema definition using helpers provided by NestJS and Mongoose. The following snippet is an example with a declaration of index setting and an o...

Fibonacci In Javascript Using Generator Function and Iterable

Generating the Fibonacci sequence is usually demonstrated in computer science courses to show an implementation of a recursive function. Besides the recursive function, we can utilize the generator function in Javascript for generating the sequence. Let us take a look at a few methods that we can perform. For instance, we will create some functions to get the value of a certain position in the Fibonacci sequence. Then, we will measure up the performance to get solid ground on what we should choose in our application. Recursive Function This is the simplest method for getting the value in the sequence. We use 1, not 0, as starting position to make this function more human. function getFibonacci1(pos) { if (pos === 1) { return 0; } if (pos === 2) { return 1; } return getFibonacci1(pos - 1) + getFibonacci1(pos - 2); } Generator Function In this method, we create a generator function for generating sequence and the actual function for providing the result. The ...

Setting Up Next.js Project With ESLint, Typescript, and AirBnB Configuration

If we initiate a Next.js project using the  create-next-app tool, our project will be included with ESLint configuration that we can apply using yarn run lint . By default, the tool installs eslint-config-next and extends next/core-web-vitals in the ESLint configuration. The Next.js configuration has been integrated with linting rules for React and several other libraries and tools. yarn create next-app --typescript For additional configuration such as AirBnB, it is also possible. First, we need to install the peer dependencies of eslint-config-airbnb . We also add support for Typescript using eslint-config-airbnb-typescript . yarn add --dev eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks yarn add --dev eslint-config-airbnb-typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser After that, we can update the .eslintrc.json file for the new configuration. { "extends": [ "airb...

Creating Connection in TypeORM

TypeORM is a complete ORM library for Node.js and other Javascript-based platforms which has support for a variety of databases such as PostgreSQL, MySQL, MongoDB, and so on. It can be utilized using Typescript or Javascript. There are several methods that can be used for creating connections in TypeORM. Create single connection await createConnection({ name, type, host, port, username, password, database }); Then, we can take the connection everywhere using getConnection() . const conn: Conection = getConnection(); Not only the connection, but we can also directly utilize EntityManager and Repository of the connection everywhere. const users = getManager().find(User); const user = getRepository(User).findOne(id); Another method is using getConnectionManager() . const connManager = getConnectionManager(); const conn = connManager.create({ ...params }); await conn.connect(); Create multiple connections await createConnections([{ ...params1 }, { ...params2 }]); Then, we ...

Compress and Decompress File/Text Content using Zlib Module in Node.js

Zlib module provides compression functionality implemented using Gzip, Deflate/Inflate, and Brotli. Compression/decompression can be used by utilizing stream directly or read the text content first. Compressing Text Content const zlib = require('zlib'); let rawStr = '--hello--world--'; let compressedStr = ''; zlib.gzip(rawStr, (err, buffer)=>{ if (!err) { compressedStr = buffer.toString('base64'); } }); Decompressing Text Content const zlib = require('zlib'); let rawStr = ''; let compressedStr = 'H4sIAAAAAAAACtPVzUjNycnX1S3PL8pJ0dUFABFjTmQQAAAA'; let inputBuffer = Buffer.from(compressedStr, 'base64'); zlib.unzip(inputBuffer, (err, buffer)=>{ if (!err) { rawStr = buffer.toString(); } }); Compression Using Stream Pipeline const stream = require('stream'); const fs = require('fs'); const zlib = require('zlib'); stream.pipeline(fs.createReadStream(...

Publish Package to NPM

NPM (Node Package Manager) is a package manger for Javascript modules/libraries. Today, there are more than 1,6 millions available packages in NPM. Before you can publish your packages or modules to NPM registry, you must create an account in  https://www.npmjs.com/ .  The steps for publishing is as follows: 1. Open terminal then login to your NPM account. npm login 2. Navigate into your package project directory. cd /path/to/your/project 3. Initiate NPM package. For preventing name conflict with other existing packages, you may specify a scope in initiating a project. npm init --scope=@your-username This action will set name property in package.json into "@your-username/your-project-name" . 4.  If you use versioning tools like Git in your project, you should set the current version of the project and align it with version property in package.json file. git tag -a v0.1.0 -m "First version for testing app." git push origin v0.1.0 ...