One place for hosting & domains

      Using Redis Transaction Blocks

      Redis is an open-source, in-memory database used for caching, messaging, and other storage tasks that benefit from fast execution and low latency. The Redis database supports a high degree of control over parallel executions that allow you to fine-tune its performance.

      This guide walks you through using Redis’s transaction blocks. Transaction blocks group Redis commands and execute them as single units. Doing so guarantees uninterrupted sequential execution of each set of commands. This ensures that all of the commands in a transaction block are executed, even in highly parallel environments.

      Before You Begin

      1. Familiarize yourself with our
        Getting Started with Linode
        guide and complete the steps for setting your Linode’s hostname and timezone.

      2. This guide uses sudo wherever possible. Complete the sections of our
        Securing Your Server
        guide to create a standard user account, harden SSH access, and remove unnecessary network services.

      3. Update your system.

        • On Debian and Ubuntu, use the following command:

          sudo apt update && sudo apt upgrade
        • On AlmaLinux, CentOS (8 or later), or Fedora, use the following command:

          sudo dnf upgrade
      4. Follow the instructions in our
        How to Install and Configure Redis
        guide to installing a Redis server and command-line interface (CLI). Be sure to use the drop-down menu at the top of that page to select your Linux distribution and get the appropriate steps.


      The steps written in this guide are for non-root users. Commands that require elevated privileges are prefixed with sudo. If you’re not familiar with the sudo command, see the
      Linux Users and Groups

      What Are Redis Transactions?

      Redis Transactions are a group of commands that are executed collectively and sequentially. The benefits of executing commands as transaction blocks are to ensure the following:

      • The sequence of commands is not interrupted, even by another Redis client
      • The commands are executed as an atomic unit and the entire transaction block is processed collectively

      Transactions are especially useful in environments with numerous clients, and where clients are making frequent transactions in parallel. Redis’s transaction blocks ensure that a given set of commands executes as a unit and in a predetermined order.

      Transaction Blocks vs. Pipelines

      Redis pipelining is another method used to optimize command execution in a highly parallel network. Pipelining in Redis allows clients to queue a series of commands and send them to the server simultaneously, rather than in multiple round trips.

      It may seem like transaction blocks and pipelining serve similar purposes. However, each has a distinct goal and acts to optimize command execution in very different ways from the other. Some of the differences are:

      • Pipelining is concerned primarily with network efficiency. It reduces the round-trip time for a series of commands by submitting them all in one request, rather than a series of requests each with its own response.

        Pipelining is useful for reducing latency and increasing the feasible number of operations per second.

      • Transactions are concerned with the integrity of a group of commands. They ensure that the entirety of a designated group of commands gets executed sequentially and without interruption. This is in contrast to pipelines that may execute requests in alternation with requests sent from other clients.

        Transaction blocks are useful when you need to guarantee a collection of commands is processed as a unit and the commands are executed sequentially.

      How to Run a Transaction Block

      To start a transaction in Redis, use the following command in the Redis CLI:


      The MULTI command begins a new transaction block. Any subsequent commands you enter are queued in sequence. To end the queuing of commands and complete the transaction block, use the following command:


      The commands displayed below include a complete example of creating a transaction block with the MULTI and EXEC commands. It starts with the MULTI command to initiate a transaction block. Then it creates a new key with a value of 10 and increments that key’s value by one. The key is then reset to 8 and again increments the value by one. Finally, the EXEC command completes the block and executes the transaction.

      SET the_key 10
      INCR the_key
      SET the_key 8
      INCR the_key
      GET the_key

      Notice that, for each command within the block (between MULTI and EXEC), the client responds with QUEUED. Once you send the EXEC command, the server provides an appropriate response for each command within the transaction.

      1) OK
      2) (integer) 11
      3) OK
      4) (integer) 9
      5) "9"

      How to Handle Errors in a Transaction Block

      When working with Redis transaction blocks, there are two kinds of errors that you may encounter. Based on when they occur, the errors can be categorized as follows:

      • Errors before the EXEC command:

        These include errors related to syntax or related to server restrictions, like maximum memory. Although you can continue queuing commands after receiving one of these errors, the transaction block subsequently fails when you run EXEC.

        For example, the transaction below includes a typo for the GET command:

        SET new_key "alpha"
        GRT new_key
        (error) ERR unknown command `GRT`, with args beginning with: `new_key`,

        Disregarding the error and attempting to execute the transaction results in an error.

        (error) EXECABORT Transaction discarded because of previous errors.

        For this reason, you should cancel any transaction blocks that encounter errors during queuing. See the next section —
        How to Cancel a Transaction Block
        — for instructions on how to do so.

      • Errors after the EXEC command:

        These are errors returned by the server in response to individual commands in the transaction. For example, you might receive such an error due to mismatched types:

        SET new_key "beta"
        LPOP new_key
        1) OK
        2) (error) WRONGTYPE Operation against a key holding the wrong kind of value

        Notice that the first command was executed successfully, which you can further verify using the GET command:

        GET new_key

      How to Cancel a Transaction Block

      A transaction can be canceled at any time before the EXEC command. To do so, use the DISCARD command.

      The example below demonstrates that the key, another_key remains unchanged from its pre-transaction value:

      SET another_key "gamma"
      SET another_key 2
      INCR another_key
      GET another_key

      As mentioned above, the ability to cancel an in-progress transaction becomes especially handy if you encounter an error while queuing commands for a transaction.


      Redis transaction execute a collection of commands and ensure that the command execution is not interrupted by another client. This guide covered creating transaction blocks, understanding common transaction errors, and canceling in-progress transactions.

      You can learn more about Redis and how to get the most out of your Redis databases through our other guides in this series. These guides cover everything from
      connecting to a remote Redis server
      to working with the
      hash data type

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.

      Source link

      A Javascript Objects Tutorial

      Objects play a fundamental role in JavaScript and appear just about everywhere throughout the language. This tutorial explains what JavaScript objects are and discusses object properties, methods, and prototypes. Each topic includes examples to illustrate their concepts.

      Before You Begin

      This guide’s JavaScript examples were originally run in the Node.js interpreter. You can use our
      How to Install and Use the Node Version Manager NVM
      guide to install Node.js on your computer.

      Alternatively, you can use your web browser’s JavaScript console to run this guide’s example JavaScript code.

      • If you are using Chrome, refer to Google’s
        Run JavaScript in the Console
        documentation to learn how to access their developer tools..

      • If you are using Firefox, refer to Mozilla’s
        Browser Console
        documentation to learn how to access their developer tools..

      What Are JavaScript Objects?

      The object is the fundamental data type in JavaScript, outside of primitive data types like numbers, strings, booleans, etc.

      An object is a collection of properties. A property is a key-value pair. In JavaScript, nearly anything can be a property. This includes not just primitive data types, but also functions and other objects.

      The next couple of sections further explain JavaScript objects, properties, and methods. They also provide examples on how to use JavaScript objects.

      JavaScript Object Properties

      Objects consist of zero or more properties. These can be either primitive data types (boolean, number, string, etc.), methods (that is, functions operating within an object), or other objects.

      Each property has a key, which can be an identifier, a number, or a string. Most of the time, identifiers are used, like in the example below of a house object:

      const house = {
          address: "123 Street Rd",
          bedrooms: 2,
          baths: 1.5,
          vacant: true,
          phoneNumber: "123-456-7890",
          inquire:  function() {
              console.log("Calling " + this.phoneNumber + "....");

      Typically, you access properties using dot notation. The example accesses the value of the address property:

      '123 Street St'

      You can also use bracket notation, as shown in the example below. Sometimes, bracket notation is required, like when a property’s key is a number or when you want to reference a key using a variable:

      let currentKeyOfInterest="vacant";

      If you want to list all of the properties of an object, you can use the Object.keys method:

      [ 'address', 'bedrooms', 'baths', 'vacant', 'phoneNumber', 'inquire' ]

      The fact that the method returns an array makes it useful if you want to iterate through an object’s properties. The example JavaScript for loop iterates over the keys of the house object created at the beginning of this section:

      for (const key of Object.keys(house)) {
          if (typeof house[key] != 'function') {
              console.log("==\t" + key.padEnd(16) + "\t=>\t\t" + String(house[key]).padEnd(16) + "\t==\t");
      ==  address             =>      123 Street St       ==
      ==  bedrooms            =>      2                   ==
      ==  baths               =>      1.5                 ==
      ==  vacant              =>      true                ==
      ==  phoneNumber         =>      123-456-7890        ==

      JavaScript Object Methods

      Any property that defines a function is called a method. These properties allow objects to take an action. For example, the inquire() method on the house object above prints a message to your JavaScript console. The example below calls the inquire() method:

      Calling 123-456-7890....

      Methods have direct access to an object’s other properties, making them especially useful for processing information on an object. You can see this in the inquire() method itself. It takes the phoneNumber property from its parent object and processes it into a message for the user.

      JavaScript Object Self Reference

      JavaScript’s this keyword gives objects a way to reference their own properties. You may have noticed its use in the inquire() method. The method is able to reference this.phoneNumber to work with the property’s assigned value.

      Below is another example. This example uses dot notation to extend the existing house object with a new method. That method then uses the this keyword to reference two properties on its parent object:

      house.bathToBedroomRatio = function() {
          return this.baths / this.bedrooms;

      How to Create a JavaScript Object

      JavaScript offers you a few different ways to create objects. Each one has its own characteristics, so which one you use depends on your needs. The next sections walk you through each approach and explain their advantages with examples.

      Using an Initializer

      Object initializers provide the most direct approach for creating an object. You can see it used to declare the house example in the
      JavaScript Object Properties
      section. With this approach, you declare your object as a variable using object literal notation.

      It has the advantage of being straightforward and is useful when declaring a standalone object that does not need inheritance.

      Below is another example of the object initializer approach:

      const socrates = {
          name: "Socrates",
          role: "Philosopher",
          fingers: 10,
          mortal: true

      Using the Object.create() Method

      The Object.create() method allows you to create new objects from an existing object, which becomes the new object’s prototype.

      This method is useful when you want multiple objects using the same base and when you want to declare objects programmatically.

      The example below creates a base Person object, then uses Object.create() method to make a specific object as an instance of that base. You then only have to define the properties that differ from the new object — name and role in this case.

      const Person = {
          name: "Nemo",
          role: "None",
          fingers: 10,
          mortal: true
      const socrates = Object.create(Person) = "Socrates"
      socrates.role = "Philosopher"

      Using a Constructor

      An Object constructor is a function that defines an object type. You can then create a new object of that type using the new keyword.

      This approach gives objects a consistent underlying type, and it can create iterations of relatively complex objects with a single line of code.

      Like the Object.create() method, this approach is useful when you expect to have multiple objects from the same base or want to create objects programmatically. Using a constructor function lets you use more complex operations when initializing an object.

      The example below defines the type Person through an object constructor function. With the new keyword, the example then declares two new objects using the constructor. Despite the objects having five properties, the constructor only requires two arguments (the third is optional):

      function Person(name, role, fingers) {
 = name;
          this.role = role;
          this.fingers = fingers > 0 ? fingers : 10;
          this.mortal = true;
          this.greeting = function() {
              console.log("Hello, I'm " + + ". I'm a " + this.role + ", and have " + this.fingers + " fingers.");
              if (this.mortal) {
                  console.log("And, as you would expect, I'm mortal.");
              } else {
                  console.log("And, as impossible as it seems, I'm immortal.");
      const socrates = new Person("Socrates", "Philosopher");
      const galileo = new Person("Galileo", "Astronomer", 7);
      Hello, I'm Socrates. I'm a Philosopher, and have 10 fingers.
      And, as you would expect, I'm mortal.
      Hello, I'm Galileo. I'm a Astronomer, and have 7 fingers.
      And, as you would expect, I'm mortal.

      You can even extend your constructors using additional constructors. Below, a Philosopher constructor extends the Person constructor defined above:

      function Philosopher(name, fingers, branch) {
, name, "Philosopher", fingers);
          this.branch = branch;
          this.greeting = function() {
              console.log("Hello, my name is " + + ", and I'm a " + this.branch + " " + this.role + ".");
      const seneca = new Philosopher("Seneca", 10, "Stoic");
      Hello, my name is Seneca, and I'm a Stoic Philosopher.

      How Does JavaScript Object Inheritance Work?

      JavaScript objects are able to inherit both types and properties from parent objects. You can see this with both the Object.create() and the object constructor examples above. This is due to JavaScript’s prototype system which is discussed in the next section.

      JavaScript Object Prototypes

      Every JavaScript object holds a reference to at least one other object, called its prototype. Even the most basic object has Object as its prototype, but other objects can inherit prototypes from parent objects or from constructor functions.

      Below are two examples showing how an object can be given a prototype, one using Object.create() and the other using an object constructor. Each example uses the following Animal object for the prototype:

      const Animal = {
          name: "",
          kingdom: "Animalia",
          phylum: "Chordata",
          class: "Mammalia",
          family: "",
          genus: "",
          species: ""
      • Objects created using the Object.create() method automatically have the parent object as a prototype. You can see from the output below that only the three properties reassigned for the indus_dolphin object show up on that object instance. All of the other properties are stored on the prototype, Animal:

          const indus_dolphin = Object.create(Animal);
 = "Indus River Dolphin";
 = "Platanistidae";
          indus_dolphin.genus = "Platanista";
          indus_dolphin.species = "Platanista minor";
        [ 'name', 'family', 'genus', 'species' ]
          name: '',
          kingdom: 'Animalia',
          phylum: 'Chordata',
          class: 'Mammalia',
          family: '',
          genus: '',
          species: ''
      • Objects created using object constructors receive values from the constructor’s prototype property. In this example, the constructor assigns the provided values. Then, a prototype is given for the constructor, which provides the resulting object, ganges_dolphin, with a prototype object:

          function Platanista(species_name, species) {
     = species_name;
              this.species = species;
          Platanista.prototype = Animal;
 = "Platanistidae";
          Platanista.prototype.genus = "Platanista";
          const ganges_dolphin = new Platanista("Ganges River Dolphin", "Platanista gangetica");
        [ 'name', 'species' ]
          name: '',
          kingdom: 'Animalia',
          phylum: 'Chordata',
          class: 'Mammalia',
          family: 'Platanistidae',
          genus: 'Platanista',
          species: ''

      Each object holds a reference to its parent prototype. This ends up creating what is called a prototype chain, connecting back from one prototype to the next. This continues until the Object prototype is reached. (Object itself actually has null as a prototype, which technically is what ends the prototype chain.)

      So, for the indus_dolphin object above, the prototype chain would be: indus_dolphin -> Animal -> Object.

      Objects can access properties from their prototype chains. When you try to access a property on an object, JavaScript starts by looking on the object itself. If it does not find the property there, JavaScript moves backward through each prototype in the chain. It keeps doing this until it either finds a prototype with the property or reaches the end of the chain.

      For example, the first of the commands below fetches the name property off of the ganges_dolphin object directly. But the second command needs to look on the prototype object to find the kingdom property. Finally, the valueOf method actually belongs to the Object prototype:
      'Ganges River Dolphin'
      { name: 'Ganges River Dolphin', species: 'Platanista gangetica' }


      JavaScript objects underpin much of the power available in the language. Objects give you access to their properties and methods. You can extend Objects after creating them and also create new Objects based off of existing ones. This guide provided an introduction to the main concepts behind JavaScript objects, including constructors, the this keyword, object inheritance.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.

      Source link

      Accessing the Document Object Model with JavaScript

      The Document Object Model (DOM) is a language-agnostic interface that provides access to an HTML document’s structure and content. JavaScript is often the language used to access the DOM in order to generate dynamic and interactive web pages.

      This guide provides an overview of the Document Object Model and shows you how to interact with it using a series of JavaScript examples.

      Before You Begin

      The examples in this guide use a web browser’s developer tools to view the DOM and interact with a JavaScript console. To get the most out of the information in this guide, follow along in your own Chrome or Firefox browser.

      • On Chrome, refer to Google’s
        Open Chrome DevTools
        documentation to learn how to access their developer tools.

      • On Firefox, refer to Mozilla’s
        Open the Inspector
        documentation to learn how to access their developer tools.

      What Is the Document Object Model?

      The Document Object Model (DOM) is an interface that provides access to an HTML document’s structure and content. The DOM represents the elements and content of an HTML document as nodes and objects. The DOM representation can then be accessed and modified by JavaScript and other scripting languages.

      Essentially, the DOM is what allows web pages to become dynamic. Languages like JavaScript work with the nodes that make up the DOM to dynamically and interactively change a web page’s presentation.

      There are many ways of displaying the DOM. One of the most widely used ways is the HTML format. When you open your browser’s Inspect dashboard, you can view the HTML representation of a web page. The example below shows the HTML markup for a simple web page.

      <!DOCTYPE html>
          <title>Example Page</title>
          <p>Example page content.</p>

      How the DOM Differs from HTML Source Code

      The DOM itself is not equivalent to a web page’s HTML source code. Instead, the DOM is a representation of how a web page is displayed in the moment that it is accessed.

      To illustrate how the DOM and HTML source code can differ, the example below displays an HTML source file. The HTML file includes a JavaScript function that adds additional HTML elements to the page once the page loads.

      File: example-page.html
      <!DOCTYPE html>
          <title>Example Page</title>
              function addExampleList() {
                  const exampleList = document.createElement("ul");
                  const exampleListItem1 = document.createElement("li");
                  const exampleListItem1Text = document.createTextNode("First item");
                  const exampleListItem2 = document.createElement("li");
                  const exampleListItem2Text = document.createTextNode("second item");
        <body onload="addExampleList();">
          <p>Example page content.</p>

      Once the HTML page is loaded and the JavaScript runs, the DOM representation of the HTML source above resembles the code displayed below. The JavaScript has been left out to make the resulting HTML easier to read. The HTML now includes an unordered list (<ul>...</ul>) with two list items (<li>...</li>).

      <!DOCTYPE html>
              <title>Example Page</title>
          <body onload="addExampleList();">
              <p>Example page content.</p>
                  <li>First item</li>
                  <li>Second item</li>

      Since the DOM is concerned with displaying the current state of an HTML page, it now displays the new HTML elements that were added to the page by the JavaScript. The DOM always reflects any additions, subtractions, or other modifications that happen to a web page. This characteristic is what enables the DOM to make web pages dynamic.

      The Document Object Model and JavaScript

      Most often, JavaScript is how web developers interact with the DOM. JavaScript is able to access the DOM with the document object and the nodes nested under it.

      The next sections explain what the document object is and the parts that make it up.

      Document Object

      To work with the DOM, client-side JavaScript provides the document object. This object includes properties and methods to access and modify the DOM.

      The previous section included some examples of the document object in action. Below are two additional commands that show more of the document object’s features.

      1. The document object’s properties provide information about the HTML document or access to its nested nodes. They also allow you to modify characteristics of the DOM as shown in the example below: = "blue";

        The example JavaScript accesses the document object’s backgroundColor property and sets its value to "blue". The web page it modifies should now have a blue background. The DOM representation of the change looks as follows:

        <!DOCTYPE html>
                <title>Example Page</title>
            <body onload="addExampleList();" style="background-color: blue;">
                <p>Example page content.</p>
                    <li>First item</li>
                    <li>second item</li>

        The color blue is assigned to the <body> element using the style attribute.

      2. The document object has several methods that do everything from provide access to specific nodes to add new nodes to the DOM. In the example below, the getElementsByTagName() method grabs every HTML element with the tag name, <li>. The JavaScript loops through those elements, and then outputs each elements textContent attributes.

        for (item of document.getElementsByTagName("li")) {

        Using the for loop above, the JavaScript console should display the following output:

        First item
        Second item

      Nodes and Elements

      The document object contains numerous other objects that all make up the DOM. These objects are called nodes. Nodes include everything from HTML elements, to attributes, to text.

      You are likely to work most frequently with element nodes. DOM element nodes correspond to a web page’s HTML elements. They allow you to access and manipulate the building blocks of a web page.

      The script used in the
      How the DOM Differs from HTML Source
      section added a <ul> element and <li> elements to the page. This added the following two kinds of nodes to the page:

      • Element nodes, which were created using the document.createElement method.
      • Text nodes, created with the document.createTextNode method.

      Each part of the document object is actually a node of some kind or other. Additionally, each node inherits common properties, like the appendChild method, which lets elements add text nodes.

      The document object does more than just let you extend the DOM. For instance, you can also use it to navigate the DOM and make precise modifications to it. The script below demonstrates how these modifications can be made to the DOM. Access the
      page in your browser. Then, open your browser’s JavaScript console, and enter in the following JavaScript:

      const listItems = document.getElementsByTagName("li");
      for (item of listItems) {
          const newTextNode = document.createTextNode(item.textContent.replace("item", "thing"));
          item.innerHTML = "";

      As a result, the DOM is updated and the text, item, contained within the <li> tags is updated to thing.

      <!DOCTYPE html>
              <title>Example Page</title>
            <body onload="addExampleList();">
              <p>Example page content.</p>
                  <li>First thing</li>
                  <li>Second thing</li>

      See our guide
      Traversing the Document Object Model with JavaScript
      , to learn about other built-in document object methods.


      The DOM provides an interface to an HTML web page. This enables you to manipulate the structure and content of a web page using scripting languages, like JavaScript. This guide introduced you to the DOM and demonstrated how JavaScript is used to add, modify, and remove HTML elements from a web page.

      More Information

      You may wish to consult the following resources for additional information
      on this topic. While these are provided in the hope that they will be
      useful, please note that we cannot vouch for the accuracy or timeliness of
      externally hosted materials.

      Source link