Join our newsletter for more DECODE content!

No thanks
📝 All
📡 Discover
🔥 Hot
06/28/2023

Monitoring Variables for Changes

All frameworks have this ability, but what if you wanted to do it in plain JavaScript? In this tutorial, we will explore how to track the state of your application and update the DOM on the fly.

In a project I am currently working on, I cannot use any frameworks due to the nature of the environment it will run in. So I went about making a traditionally built site however, I have been using Svelte so much recently I could barely stand having to keep the DOM synced with the data behind the scenes. So I attempted to create a mini framework that would help keep everything up to date. This isn't about the framework I made for myself, this is about creating reactivity in a traditional application without manually keeping track of the data.

I found the easiest way to implement this is to use a borrowing system. Where a function asks for a variable from the object the state is stored in and returns the updated value once complete. After the value is updated rerunning every function that uses the changed variable.

To give context for all the code we will be talking about, here is the shell of the constructor function. We will use this to contain the state of the document and the methods will be used to interact with the state.

javascript
function State(v) {
    let context = {};
    let dependencies = {};
Read

Comments


Be the first to comment!

06/16/2023

Using Sever Sent Events as Light Weight "WebSockets"

Until recently I never completely understood what server-sent events were. Of course, I had a general idea of how they work, they acted as a websocket that works in one direction, allowing you to send data at different times throughout a request. What I didn't realize is how simple they were to implement and how powerfull they could be.

Let's look at the implementation of server-sent events, how they work, and the cool features built in. Along with the good attributes of server-sent events, we will also look at when NOT to use them and their limitations.

Creating an SSE

Later on in this article, we will use the express library as our HTTP router, but let's first look at an implementation using the raw HTTP library in Node.

javascript
const http = require("http");

function handle(req, res) {
Read

Comments


Be the first to comment!

06/09/2023

Paraphrasing Text without Machine Learning in JavaScript

Being able to summarize a article is super useful and surprisingly it doesn't require machine learning to accomplish. Here we will go over the concepts behind frequency analysis and implement it to build a text summerization api.

The type of summarization we will be doing here is called "extractive summarization", extractive summarization relies on selecting the most important sentences in the text and combining them in a way that makes sense. The advantage of using algorithmic summarization over a machine learning approach is speed and cost. Algorithmic summarization trades off quality over speed and accessibility. However, in most cases, the quality of the extracted summarization is high enough not to matter.

How it works

The steps in extractive text summarization are first to break apart the sentences of the inputted text. This can be done using a regex approach like the one below.

javascript
function breakSentence(sentences) {
    return sentences
        .replaceAll(/\s+/g, " ")
Read

Comments


Be the first to comment!

05/27/2023

Redirecting Users to the Correct Page After a 404 Error

Properly addressing 404 errors is crucial in preventing the loss of traffic to your website. In this tutorial learn how to rectify this error and redirect users to the right page.

In this tutorial, we won't be discussing how to create a 404 page as it's a relatively simple process and can be personalized to your liking. Instead, I'll be addressing a common issue - when a user enters a wrong URL, how can we redirect them to their intended destination? This is crucial in terms of both user experience and overall usability. As a website owner, I want to ensure that my users can access my content with ease, and I'll share some effective methods to achieve this.

First off you will need a list of every accessible URL on your site, this can be an RSS feed or a sitemap.xml for this site. I will be using a RSS feed for this example but it doesn't matter what it is. We will take the feed and use RegExp to parse the URLs from the text like below.

javascript
let urls = rss_feed.match(
                /\b((https?|ftp|file):\/\/|(www|ftp)\.)[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/gi
            );
Read

Comments


Be the first to comment!

05/23/2023

Improving Node JS performance by 400% with Turb.js

Turb.js is a function caching server that turbo charges your application with safe and fast memory management. Today we will use Turb to increase the performance of static assets in our PocketBase database. Although this example is for PocketBase, Turb can be used anywhere in your application to speed up long processes.

From the description we know that turb is a function caching server, but what does that mean? Turb acts as an intermediate layer between your database's SDK and your application by storing each function call in memory. After the response is stored in memory, you won't have to request the asset from your database again! After I added turb to this site, I saw a 4x decrease in load times.

Installing Turb

text
npm i turb

Building the server

Read

Comments


Be the first to comment!

05/22/2023

How to setup Nginx server blocks for multiple sites - Ubuntu

Setting up nginx server blocks is a process that allows you to host multiple websites on a single server. It is a useful technique for those who want to host multiple websites or applications on a single machine, as it allows you to use a single IP address and port to host multiple domains. In this article, we will explain how to set up nginx server blocks on a Ubuntu server.

Nginx Logo

Prerequisites

Step 1

Allow Nginx to pass through your firewall.

sudo ufw allow 'Nginx HTTP'
Read

Comments


Be the first to comment!

05/18/2023

Benchmarking Node JS vs Bun

Recently Bun added a compiling feature in version 0.6.1. Curious about its functionality, I conducted a comparison between compiled and uncompiled versions as a baseline. I also tested it against Node JS compiled with pkg. Here are the results!

Results

Read

Comments


Be the first to comment!

05/14/2023

Ditch Algolia, Create Your Own Content Search Engine

Build a full-text search engine with autocorrect for the content of your website that directly connects to your database. Users being able to find the content they want on your site is essential. Out-of-the-box solutions like Algolia are great, but it probably isn't the best use of resources for a small website. With this tutorial, we will use flexsearch to search documents and use some custom code to make the result 10x better.

This tutorial is designed to be platform-neutral and can be used with any database, server, or framework. While we'll be focusing on setting up an express server, the search function can easily be adapted to work in any part of your application. After configuring the server, we'll implement the autocorrect feature and leverage flexsearch to locate relevant documents.

Dependences

text
npm i express flexsearch stopword closest-match
  • express
    • Acts as a middleware for our web server
  • flexsearch
Read

Comments


Be the first to comment!

05/03/2023

Promise Message Queuing

When building an application, if you are like me, you make multiple requests to your database per request. I recently ran into an issue with syncing the fetching of data from my database and returning a response as soon as possible. Here's how I fixed it.

The Problem

Three database queries are running on the server side of this website's homepage. One to get the site's styling, one to get the posts, and the last to get the series listed on the sidebar. Previously, I was chaining the queries to run one after another, in hindsight this is a bad idea because you have to wait the sum of the three requests time before the site responds. This causes the initial response from the server to be slow, but it was nothing too crazy. Here is the code version of how it was laid out.

javascript
DB.get("styles")
    .then(() => {
        DB.get("posts")
            .then(() => {
                DB.get("series")
                    .then(() => {
Read

Comments


Be the first to comment!

04/29/2023

TF-IDF Visualizer

TF-IDF stands for Term Frequency - Inverse Document Frequency, the formula we will be going over in this document is used to measure the importance of a word in a sentence. This is heavily used in machine learning and data mining to identify stopwords and select sentence that can be used to form a summary.

Below are three documents (Lorem ipsum) and a target word selector, the target word is the word you want to calculate the TF-IDF for. Further down, we will go over how to calculate the weights and what they mean.

Document
Document 2
Read

Comments


Be the first to comment!

04/25/2023

Running Spreadsheets in the Browser

Spreadsheets are used everywhere in business and just about everyone knows how to use them at least at the surface level. If you want to build functionality into your website or blog post without building out a complete system you could opt to embed a spreadsheet instead.

For the spreadsheet parser we will be building, we will use a table tag with a spreadsheet attribute and a data attribute that will contain the CSV data in the form of a two dimensional array. The size of the spreadsheet will be determined by a set of rows and cells attributes and the complete tag will look like this:

html
<table
    spreadsheet
    cells="100"
    rows="20"
    data='[["Item","Cost"], ["Rent","1500"], ["Utilities","200"],["Groceries","360"], ["Transportation","450"], ["Entertainment","1203"], ["Total","=SUM(B2:B6)"]]'
></table>
Read

Comments


Be the first to comment!

04/20/2023

Building a Highlighted Text Editor in the Browser

Trying to get highlighted code to be editable on your website can be tricky to implement. The idea behind successfully doing it is to display a code tag and highlight the code in there, then overlay a textarea with the font color and background set to transparent.

Now that you know what we will build, let's learn how to implement it.

Code Highlighting

We will need to highlight the code in the editor we are building, so for this, we will use the library I use, and the most popular, highlight.js.

Importing

All of the code we will go over here will be in the browser, but highlight.js is an NPM package, so we can use unpkg to host our files. Highlight.js needs at least two files, the javascript and the CSS styling. If you want to use a non-default CSS layout, you can pick one from here.

JS
html
Read

Comments


Be the first to comment!

04/16/2023

Building a CodePen Type Editor from Scratch

Wanting to show live examples of code on your website is very common, if you want to do it today there are a few services that provide that ability. However, if you are like me, you would rather roll your own. In this tutorial, I will be building my own codepen like editor for this site.

My goal with this is more complex than most people's use case because this site uses a markdown compiler called MDXT (this is a custom compiler made for this site); I want to include the code here into the MDXT language. So with that in mind, I will have two versions and review how each works. The first version will cover how to link the textarea inputs with the iframe and dynamically update it. The second one will keep the core aspects of the first but will be designed to handle multiple editors on the same page.

To keep this document clean, I will not include the boilerplate HTML in the examples, but if you need it, type doc into VSCode and paste the examples in the body tag.

Stand Alone Editor

Starting with the editor's markup, we will have three <textarea> tags in the body of the page along with a <iframe>. If you jump ahead and look below, you can see each textarea has a data-lang attribute. This will give us a very sexy method of interacting with the document updater when we get to that point. I am not including styles with this tutorial because I have yet to style my editor. ...

html
<textarea data-lang="html" cols="30" rows="10"></textarea>
<textarea data-lang="css" cols="30" rows="10"></textarea>
Read

Comments


Be the first to comment!

04/13/2023

NodeJS/Javascript Testing Using the Test Runner Module

The test runner API is a new set of built-in tools allowing you to natively create tests for your code. No more need for Jest, Mocha, or Ava! This will bring Node up with most modern languages (Dart, Rust, GO) and reduce the package size of your code base.

The test runner API is not a drop-in replacement for other frameworks, so you must migrate all of your tests to the new syntax. However, its syntax is very straightforward and takes inspiration from the existing frameworks. This will make transitioning to the built-in test runner much easier.

Getting Started

Installing Node v19.0.0

To get the latest version of Node, you can either install version v19.0.0 from the Node.JS website here, or you can install nvm. NVM is a node version manager, allowing you to run multiple versions of Node on your computer.

Installing NVM
bash
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh | bash

To install Node v19.0.0

Read

Comments


Be the first to comment!

04/13/2023

Round Up #1

A round up of important tech related news that happened this week. Including Dolly, Databricks open source LLM. Node JS has released an official test runner and more.

DECODED

Node JS is coming out with built-in testing

SHORT: With the newest release of Node v19.9.0, Node is getting a built-in test runner.

LONG: The test runner API is a new set of built-in tools that will allow you to create tests for your code natively. No more need for Jest, Mocha, or Ava! This will bring Node up with most modern languages (Dart, Rust, GO) and reduce the package size of your code base. It is not a drop-in replacement for other frameworks, so you will need to migrate all of your tests to the new syntax. However, the test runner syntax is very straightforward and takes inspiration from the existing frameworks. This will make transitioning to the built-in test runner much easier.

Read

Comments


Be the first to comment!