Skip to main content

Posts

Showing posts from June, 2021

Create Multi-stage Dockerfile for Development and Production

By utilizing container technology like Docker, we can have an identical environment for development and production. But, working in a development environment requires us to be able to change the source codes directly. We can define multi-stage procedures in the Dockerfile and specific commands to run the container. For example, we have a Node.js program that will be shipped using a container. 1. Create a Dockerfile with stages for development and production. # syntax=docker/dockerfile:1 FROM node:14.17.1 as base WORKDIR /app COPY ["package.json", "package-lock.json", "./"] FROM base as development ENV NODE_ENV=development RUN npm ci COPY . . CMD ["nodemon", "-L", "app.js"] FROM base as production ENV NODE_ENV=production RUN npm ci --production COPY . . CMD ["node", "app.js"] In this example, the program for development is run using nodemon  therefore we need to install nodemon first by npm i -D node...

Film Action dan Misteri Asia Terbaik

 Ini adalah beberapa film action dan misteri asia yang bagus menurut saya.  1. New World (2013) Sekelompok polisi ditugaskan menyamar sebagai bagian dari kelompok mafia untuk mengungkap skandal korupsi yang ada. Namun, hubungan yang kemudian terbangun kuat di dalamnya, membuat seorang polisi meragukan siapa yang benar, siapa temannya yang sesungguhnya, dan siapa yang harus dibela. 2. A Hard Day (2014) Film ini menceritakan seorang polisi yang mengalami sebuah kecelakaan saat mengendarai mobilnya yang kemudian malah menggiringnya ke sebuah kasus besar yang tidak terduga dan membuatnya harus berhadapan dengan musuh yang menyeramkan. Benar-benar hari yang berat. 3. Alive (2020) Ini adalah film dengan tema zombie. Ada seorang pemuda yang terperangkap di dalam komplek apartemennya ketika serangan zombie datang. Dia sempat frustasi karena tidak adanya pertolongan, namun ternyata ada survivor lain yang akhirnya dapat membantu dia untuk menyelamatkan diri dan tetap hidup. Salah satu a...

Running Cluster of Node.js Processes on Multi-Cores System

By default, a Node.js program runs as a single-thread application. For utilizing all available cores in your system, you can use the cluster module in Node.js. This module can fork specified processes in your program into several processes that run on the desired number of available cores. For example, you have a server that accepts a client request, generates random characters, and sends back a response. For the purpose of increasing the load, the random characters generator will redo its process 10,000 times. Then, you will make 100 requests to the server in a time to force your server application for spawning new handler processes. 1. Create this sample server program server.js . const http = require('http'); const cluster = require('cluster'); const coreNumber = require('os').cpus().length; // define server object const server = http.createServer(function(req, res){ console.log(`Handled by PID ${process.pid}.`); // do expensive computation let al...

Multiple Background Layers in CSS

If you want to customize a background with multiple layers in CSS, it is possible with background-image property by defining more than one valid background values separated by comma except plain color value. It means you can add several url('...') values but not for #010101 color value. For defining a layer with plain color, you can utilize liniear-gradient with same start and end color value, for example liniear-gradient(to right, #010101, #010101) . Below are some examples. Set an image on top of colored background. background-image: url('image.png'), linear-gradient(to right, #010101, #010101); Set color overlay on top of image. background-image: linear-gradient(to right, rgba(100, 100, 100, .6), rgba(100, 100, 100, .6)), url('image.png');

What is HTTP/2?

HTTP/2 is an extended version of HTTP communication protocol after HTTP/1.1. Targets of the improvement are: Faster communication (50% improvement) Better utilization of available network capacity Keep existing application with the older version (HTTP/1.1) running (no changes required) How those targets can be achieved? There are several technical aspects: Applying header field compression Allowing multiple concurrent exchanges on the same connection (allowing interleaving request & response) No change in core concepts of HTTP such as method, status codes, URIs, and headers. HTTP/2 adds a binary framing layer in HTTP protocol that dictates how messages are encapsulated and transferred. There are several terms in HTTP/2 protocol: Stream. It is a bidirectional flow of bytes that can contain one or more messages. Frame. It is the smallest unit of messages in the stream. It has a header that contains the identity to which the stream belongs. Frame can contain encoded header data or...

Run MongoDB in Docker Container

For faster application development and delivery, Docker can be a good choice. MongoDB image has been available in the Docker registry. You can run MongoDB in Docker container then connect your application or service to it. To make the MongoDB service becomes available in the container's network and its data can be persisted, there are several steps for configuration. 1. Create named volumes  for MongoDB data and a configuration file, then create a network for containers in your application system. For example, the volumes are my-mongo-data and my-mongo-config , and the network is named my-net . docker volume create my-mongo-data docker volume create my-mongo-config docker network create my-net 2. As mentioned in MongoDB for Docker' site , database data is stored in the  /data/db directory in the container. MongoDB for Docker also accepts environment variables for setting up initial username and password for root user which are named MONGO_INITDB_ROOT_USERNAME and MONG...

My Scariest Sleep Paralysis Moment

This is a very old story. It happened when I was still a kid. This experience had made me afraid for opening my eyes in the moment of sleep paralysis for years. People may have some experiences in sleep paralysis. Many explanations also have already been available on the internet such as this WebMD article . Based on my own experiences, I have several notions of why it can happen. Personally, it can be caused by sleeping position, absence of pillow, and bad sleeping pad. But, I still have no idea about some phenomena in sleep paralysis moment like what happened to me when I was a kid. It was in fasting month and I was still in the fourth grade of elementary school. I fell asleep in front of a television on a bed beside a sofa. I slept on my side facing to the right. At one moment, I suddenly had an urge to wake up, but I couldn't move any of my limbs except my eyelid. I also feel vibrations on some areas of my body, especially on the armpit. When I opened my eyes, I saw something...

Measuring Performance of Node.js Program Using Performance Hook Module

Node.js has provided tools for measuring or benchmarking your application performance by marking certain blocks of codes and capturing the duration of the executions. For example, you have a program example.js that run two functions, generate a random string, and make a request to facebook.com , as follows. const https = require('https'); const debuglog = require('util').debuglog('example'); // 1) generate 100 digits random string let randomStr = ''; let allowedChars = 'abcdefghijklmnopqrstuvwxyz0123456789'; for (let i=0; i<100; i++) { randomStr += allowedChars.charAt(Math.floor(Math.random() * allowedChars.length)); } debuglog('Random String:', randomStr); // 2) make a request to facebook.com let request = https.request({ protocol: 'https:', hostname: 'facebook.com', method: 'GET', path: '/' }, (res)=>{ if (res.statusCode) { debuglog('Request Status Code:', res.statusCod...

Shipping Node.js-based Application as Docker Image

Docker is a set of tools for managing and delivering services or application components as isolated packages called containers. This technology become more popular in present time along with increase in demand of micro-services architecture, continous integration, and faster features or services delivery. This article shows you how to ship your Node application as Docker image and deploy it as a container. 1. Initiate a Node project. mkdir my-node-app cd ./my-node-app npm init -y 2. Write a sample Node application named server.js in your project directory. const http = require('http'); const chalk = require('chalk'); const server = http.createServer(function(req,res){ res.end('Hello from Node server.'); }); server.listen(5000, ()=>{ console.log(chalk.green('Your server is running on port 5000!')); }); 3. Install your Node application dependency. npm install --save chalk 4. Write a Dockerfile file in your project directory. # s...

Getting Host System Status in Node.js

Node.js has been shipped with modules that can enable our application to retrive information about the system status suh as memory usage, platform of OS, number of CPUs, etc. Those modules are OS and V8 . Some usage examples are as follows. const os = require('os'); const v8 = require('v8'); console.log('Platform:', os.platform()), console.log('Number of CPUs:', os.cpus().length), console.log('Free Memory:', os.freemem()), console.log('Current Malloced Memory:', v8.getHeapStatistics().malloced_memory), console.log('Peak Malloced Memory:', v8.getHeapStatistics().peak_malloced_memory), console.log('Size Limit of Heap Memory:', v8.getHeapStatistics().heap_size_limit), console.log('Total Heap Memory:', v8.getHeapStatistics().total_heap_size), console.log('Used Heap Memory:', v8.getHeapStatistics().used_heap_size), Heap memory is space of memory that is allocated for storing dynamic objects in Node.js

Installing Multiple Instances of Linux Distributions in WSL

By support of WSL (Windows Subsystem for Linux), you can install any Linux distros in a Windows machine. Recommended method from WSL documentation is by downloading the distribution from Microsoft Store or find .appx installation file available in Microsoft website. For running multiple instances of same Linux distribution, you can duplicate the data using export-import procedure, as I have mentioned in another post . Another method that might be more beneficial is by utilizing Docker. Currently, Docker has already had variety of images of Linux distributions in its registry. You can also store your own costumized distribution in Docker registry that can be distributed to any machines instantly. After you had WSL 2 and an installed Linux distribution from Microsoft Store, you are ready to have more Linux instances in your Windows. 1. List all installed distributions in your Windows. wsl --list -v 2. Run the distribution you desired from terminal, for example, you have insta...

Creating HTTP/HTTPS Server in Node.js

Node.js has become a powerful tool for building many kinds of services on the web. It provides variety of built-in modules that can be utilized to meet any developers needs. One of common modules for web developers is HTTP module. This module can be used for handling HTTP request or building a web server. This following example shows you how to build HTTP and HTTPS server in Node.js. This sample server will accept client request and deliver response with a payload containing what the client was sent. 1. In your project directory, generate self-signed certificates that will be used for configuring HTTPS server. OpenSSL is required for this process. openssl req -nodes -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 2. Create a file named server.js . const http = require('http'); const https = require('https'); const {StringDecoder} = require('string_decoder'); // function that receives request and response parameters from HTTP/HTTPS server...

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(...

Managing WSL Data Directory/Storage

WSL (Windows Subsystem for Linux) is a great tool provided by Windows 10 (OS build 20262 or higher) that enables developers to run Linux machines in Windows platform without third-party application like Virtual Box. With support of installed WSL, you can install any Linux distribution available in Microsoft Store . After installation of a Linux distribution, for example Ubuntu 18.04, WSL stored its machine data in %APPDATA%\Local\Packages\CanonicalGroupLimited.Ubuntu18.04onWindows_79rhkp1fndgsc\LocalState . If you need to move the data to another directory/drive in your computer to free some spaces in your main drive, you can perform these following commands. 1. List all distributions in your computer. wsl --list --verbose 2. Export the distribution data. wsl --export <distribution-name> <any-file-name>.tar For example, distribution name is Ubuntu-18.04: wsl --export Ubuntu-18.04 exported-ubuntu-18-04.tar 3. Unregister the distribution. wsl --unregister Ubun...

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 ...