Join our newsletter for more DECODE content!

No thanks
πŸ“ All
πŸ“‘ Discover
πŸ”₯ Hot
01/25/2023

Building SvelteKit for Node JS

SvelteKit is a powerful tool that is great for making all types of websites, with out of the box support for services like Vercel. In this tutorial you will learn how to setup up SvelteKit for Node JS to run on a platform like Digital Ocean.

Installing the Correct Adapter

Out of the box, Svelte comes with the auto adapter, to build your app for Node Js you will have to install adapter-node.

npm i @sveltejs/adapter-node

Configuring Svelte

The svelte.config.js contains all of your adapter settings to build for Node you can set up your file like this.

Output Directory
Read

Comments


Be the first to comment!

01/24/2023

JS Chunk Array

Here's a simple function that uses generators to chunk an array. Generators are a type of function that returns an iterator and traverse it one at a time if you use the spread operator with a generator you get a very efficient function that is easy to work with.

Code

function* chunks(arr, n) {
  for (let i = 0; i < arr.length; i += n) {
    yield arr.slice(i, i + n);
  }
}

The function above takes two parameters: an array arr, and an integer n.

Read

Comments


Be the first to comment!

01/21/2023

PicoCSS product page example

Pico CSS is a great tool for building low code interfaces, today we will be going through the process of creating a product page for a ecommerce store. The image below shows what you will have at the end.

Product Page Example

The header takes advantage of Pico’s built in styles with a few lines of extra CSS.

<!β€” HTML β€”>
<nav>
    <ul>
        <li><img id="favicon" src="/logo.png" alt="Logo" /><strong class="bold">LOW</strong></li>
    </ul>
Read

Comments


Be the first to comment!

01/21/2023

DuckDuckGo Search JS

Scraping search results from DuckDuckGo's Lite page using Node.js is a great way to gather data on a specific topic or group of keywords. In this blog post, we will walk through the process of scraping search results from DuckDuckGo's Lite page using the Node.js fetch and JSDOM libraries.

First, install JSDOM by running the following command in your terminal:

npm install jsdom

We will then use the native fetch library to send a GET request to DuckDuckGo's Lite page, passing in the search query as a parameter. The response from the server will be passed to the JSDOM, which allows us to navigate and extract data from the HTML using the DOM syntax.

import { JSDOM } from 'jsdom';

/**
Read

Comments


Be the first to comment!

01/19/2023

Node JS Read File Directory

Reading a directory in Node JS can be useful for many reasons, here's a quick way to get all the file paths in an array.

function getFiles(dir) {
    return fs.readdirSync(dir).flatMap((item) => {
        const path = `${dir}/${item}`;
        if (fs.statSync(path).isDirectory()) {
            return getFiles(path);
        }

        return path;
    });
Read

Comments


Be the first to comment!

01/19/2023

Mapping Wildcard Paths - Express Endpoints

Learn how to map wildcard paths to system paths for Svelte like endpoints in Express.

This is a continuation of a series on how to build a routing system like Svelte with Express JS.

Previous Tutorials

The previous tutorial gives you a function that is able to pull all of the file paths from a directory and put them into an array. In this tutorial, we will map the file routes to endpoints that we can call and return with express.

The End Goal

The end goal is to take paths from the file system like below and extract any variables and return the full URL and variables in an object. The variables will be defined by putting the variable name inside of square brackets and the endpoint function will be a file in the last folder named +server.js.

Read

Comments


Be the first to comment!

01/17/2023

Express Plugins

Express plugins can be used to process POST body data, serve static files, or serve content with CORS enabled. Learn the basics of app.use.

First, we will start off with parsing a POST requests body. If you are familiar with Express v3.x you with know about body-parser in Express v4.x has been replaced with urlencoded, here's how to use it:

app.use(express.urlencoded({ extended: true }));

This will parse the POST request and add the data to your request object's .body property.

If your data is in a JSON format you will need to add another built-in function to parse it like below.

app.use(express.json());
Read

Comments


Be the first to comment!

01/16/2023

Node JS Express Server

Even though Node JS has a built in HTTP request handler using a web server framework can reduce the amount of code and increase the reliability of your site. There are many options to choose from however express is one of the most popular for it's easy to use syntax and wide support.

Installation

npm install express --save
Hello World

Here is a simple Hello World server that listens on port 3000. To start a server create an instance of express(), like in line 2. Add the listeners, app.get for get requests and app.post for post requests. If you followed the Node JS HTTP Webserver tutorial, express works very simular however all you need to send data is res.send. To start the server call app.listen(port) just like using the HTTP module.

const express = require('express');
const app = express();
Read

Comments


Be the first to comment!

01/15/2023

Node JS HTTP Webserver

Node JS comes out of the box with a built in HTTP module that can handle Hypertext Transfer Protocol requests. You can use this to build a web server without installing anything.

The HTTP module can be used to create an HTTP server that can process requests can write back to the client.

Importing HTTP
const http = require("http");
Processing Requests

Here is a basic HTTP server using the HTTP module in Node JS. To create the server use the http.createServer function in the HTTP library. You need to pass in a function to handle the request and the response. The request will provide you the information on what has been sent to you and the response will be what goes to the user. Responses need to have content written to them, you can use res.write to add any type of data. Then to send it you close the response with res.end. To set the port the server listens to and to start the sever, add .listen(port) to the http.createServer function.

const http = require("http");
Read

Comments


Be the first to comment!

01/14/2023

Understanding Classes in JavaScript

Classes are blueprints for creating objects (a type of data structure), providing initial values for state (using a constructor), and implementations of behavior (member functions or methods). They support inheritance and polymorphism, which are fundamental concepts in object-oriented programming.

JavaScript classes were introduced in ECMAScript 2015 (ES6) and are a way to define a constructor function and a set of methods all at once. The class syntax is a shorthand for defining constructor functions and their prototypes.

Example:

class Person {
  constructor(name) {
    this.name = name;
  }
  sayHello() {
    console.log(`Hello, my name is ` + this.name);
Read

Comments


Be the first to comment!

01/14/2023

Extracting URL Parts

JavaScript provides several built-in methods that can be used to extract different parts of a URL. Here is a tutorial on how to extract the protocol, hostname, pathname, and query parameters of a URL in JavaScript.

To extract the protocol (e.g. "HTTP" or "HTTPS") of a URL, you can use the protocol property of the URL object. For example:

let url = new URL("https://decode.sh/extracting-url-parts?query=false");
let protocol = url.protocol;
console.log(protocol); // "https:"

To extract a URL's hostname (e.g. "decode.sh"), you can use the hostname property of the URL object. For example:

let url = new URL("https://decode.sh/extracting-url-parts?query=false");
let hostname = url.hostname;
Read

Comments


Be the first to comment!

01/13/2023

Bundling NPM packages for the browser

How to bundle your NPM package for production

When building Kod.js I wanted it to work on both Node and in the browser. I had to be careful not to use modules that aren't compatible with both environments. However, once the code was written it still relied on external packages that had to be loaded separately, this clearly isn't a good way to create a package. After doing a bit of research I came across module bundlers like browserify that could make my code into one big file. Here's how to do the same:

Installing Browserify

Browserify is an open-source javascript bundler that runs as an OS-level command so you will want to install it globally.

npm install -g browserify

Using ES6 import

Out of the box, browserify doesn't support ES6 modules, you will need to install esmify to be able to bundle using browserify.

Read

Comments


Be the first to comment!

01/13/2023

Fetch API

The Fetch API is a interface for making http requests using javascript in the browser and with node version +18. If you are familiar with the XMLHttpRequest or ajax() from jQuery this will feel familiar.

Concepts

The fetch api is built on promises and returns a Response object that will need further processing depending on the data parsing you want. The fetch() function takes two arguments, the request URL and the parameters. Then returns a Response object that will further process your data.

Usage

Here is a simple example of a fetch request to an RSS feed. The RSS feed is in plain text so we process it using the response.text() method. There is also .json(), .blob(), .formData() and .arrayBuffer().

fetch('https://decode.sh/rss")
  .then((response) => response.text())
  .then((data) => console.log(data));
Read

Comments


Be the first to comment!

01/12/2023

HTTP Headers - Basics

HTTP headers are a crucial part of the HTTP protocol, which is used to transmit data over the internet. These headers are used to provide additional information about the request or response, such as the type of content being sent, the length of the content, and the encoding used.

There are several types of HTTP headers, each with its own specific purpose. Some of the most common headers include:

Content-Type

  • This header specifies the type of content being sent, such as text, HTML, or JSON. It is used by the browser to determine how to handle incoming data.

Content-Length

  • This header indicates the length of the content being sent, in bytes. It is used by the browser to determine when all of the data has been received.

Accept

  • This header is used to specify the types of content that the client is willing to accept. It can be used to specify a specific type of content, such as HTML, or a general type, such as text.
Read

Comments


Be the first to comment!

01/10/2023

Promises VS Callbacks

Promises and callbacks are both ways to handle asynchronous code in JavaScript. A callback is a function passed as an argument to another function and executed after the first function has been completed. A Promise is an object that is returned immediately, representing a value that may not be available yet. Promises are more powerful than callbacks because they provide a way to compose asynchronous operations and methods to handle errors. Promises also provide better readability and maintainability by eliminating the need for nested code blocks.

Promises

Promises are object that are returned as soon as you call them allow the thread to continue processing and will return once the process inside the promise is complete. Here is a simple example:

function oneSecond(msg) {
    return new Promise((resolve) => {
        setTimeout(()=
            resolve(msg);
        }, 1000);
    });

            resolve(msg);
        }, 1000);
    });
}
Read

Comments


Be the first to comment!