One place for hosting & domains

      Work

      How To Work with Strings in PHP


      The author selected Open Sourcing Mental Illness Ltd to receive a donation as part of the Write for DOnations program.

      Introduction

      A string is a sequence of one or more characters that may consist of letters, numbers, or symbols. All written communication is made up of strings. As such, they are fundamental to any programming language.

      In this article, you will learn how to create and view the output of strings, how to use escape sequences, how to concatenate strings, how to store strings in variables, and the rules of using quotes, apostrophes, and newlines within strings in PHP.

      Single and Double-Quoted Strings

      You can create a string in PHP by enclosing a sequence of characters in either single or double quotes. PHP will actually interpret the following strings differently:

      'This is a string in single quotes.'
      
      "This is a string in double quotes."
      

      Before output, double-quoted strings will evaluate and parse any variables or escape sequences within the string. Single-quoted strings will output each character exactly as specified. The exception for single-quoted strings is a single quote (and backslash when needed).

      If you were to echo this string in PHP:

      'Sammy says: "This string's in single quotes." It required a backslash () before the apostrophes (\'), but do not use (") with the double quotes.'
      

      It would return this output:

      Output

      Sammy says: "This string's in single quotes." It required a backslash () before the apostrophes ('), but do not use (") with the double quotes.

      If you don’t include a backslash before the apostrophe in the single-quoted string, PHP will end the string at that point, which will cause an error. Since you’re using single quotes to create our string, you can include double quotes within it to be part of the final string that PHP outputs.

      If you want to render the ' sequence, you must use three backslashes (\'). First \ to render the backslash itself, and then ' to render the apostrophe. The sequence " is rendered exactly as specified.

      "Sammy says: "This string's in double quotes." It requires a backslash () before the double quotes (\"), but you MUST NOT add a backslash before the apostrophe (')."
      

      Output

      Sammy says: "This string's in double quotes." It requires a backslash () before the double quotes ("), but you MUST NOT add a backslash before the apostrophe (').

      As with the single-quoted string, if a backslash is not included before the double quotes in the double-quoted string, PHP will end the string at that point, which will cause an error. Since the double-quoted string is not ended with a single quote, you add the apostrophe directly to a double-quoted string. A double-quoted string will output ' with either a single or double backslash used with the apostrophe.

      To output the " sequence, you must use three backslashes. First \ to render the backslash itself, and then " to render the double quote. The sequence ' is rendered exactly as specified.

      The is known as an escape character. Combined with a secondary character, it makes up an escape sequence. Now that you have an understanding of strings, let’s review escape sequences.

      Escape Sequences

      An escape sequence tells the program to stop the normal operating procedure and evaluate the following characters differently.

      In PHP, an escape sequence starts with a backslash . Escape sequences apply to double-quoted strings. A single-quoted string only uses the escape sequences for a single quote or a backslash.

      Here are some common escape sequences for double-quoted strings:

      • " for a double quote
      • \ for a backslash
      • $ to render a dollar sign instead of expanding the variable
      • n for a new line
      • t for a tab

      Here is an example of how you can use these sequences in a string:

      ""What type of $ do sharks use?"ntSand dollars!"
      

      Output

      "What type of $ do sharks use?" Sand dollars!

      Using escape sequences gives us the ability to build any string required while including these special characters.

      Creating and Viewing the Output of Strings

      The most important feature of double-quoted strings is the fact that variable names will be expanded, giving you the value of the variable. You can use a variable to stand in for a string or use a string directly. You output the string by calling the echo function:

      $my_name = "Sammy";
      echo 'Name is specified using the variable $my_name.';
      echo "n"; // escape sequence for newline character
      echo "Hello, my name is $my_name. It's stored in the variable $my_name.";
      

      The $my_name variable is created on the first line. On the second line, the echo function is used to output a string in single quotes. Using the $my_name variable within this single-quoted string displays the characters exactly as they are written, so we will see the variable name instead of its value.

      On the fourth line, we use the echo function again, but we are using double quotes this time. This time the variable is expanded to show the value in the first sentence. In the next sentence, there is a before the $ to explicitly tell the string to display a $ character and not expand the variable.

      Output

      Name is specified using the variable $my_name. Hello, my name is Sammy. It's stored in the variable $my_name.

      Note: When string evaluation is not a concern, you may choose to use either single quotes or double quotes, but whichever you decide on, you should be consistent within a program. Single quotes may be marginally faster.

      With an understanding of how to create and view the output of strings, let’s move on to see how you can manipulate strings.

      String Concatenation

      Concatenation means joining strings together, end-to-end, to build a new string. In PHP, there are two main ways to concatenate a string.

      The first is to include a string variable within a double-quoted string. This was shown in the previous step and in the following:

      $answer = "Chews wisely.";
      echo "What do sharks do when they have a big choice to make? $answer";
      

      Running this code will combine the string and the $answer variable, which is set to Chews wisely.:

      Output

      What do sharks do when they have a big choice to make? Chews wisely.

      A second way to concatenate strings is to use the . operator.

      Let’s combine the strings "Sammy" and "Shark" together with concatenation through an echo statement:

      echo "Sammy" . "Shark";
      

      This code uses the . operator to combine the "Sammy" string and the "Shark" string without a space in between.

      Output

      SammyShark

      If you would like whitespace between the two strings, you must include the whitespace within a string, like after the word Sammy:

      echo "Sammy " . "Shark";
      

      Output

      Sammy Shark

      You cannot use concatenation to combine a string with an integer:

      echo "Sammy" . 27;
      

      This will produce an error:

      Output

      Parse error: syntax error, unexpected '.27' (T_DNUMBER), expecting ';' or ',' in php shell code on line 1

      If you put "27" within quotes, it will evaluate as a string.

      PHP is a loosely typed language, which means that it will try to convert the data it is given based on the request. If you set a variable to 27, when used in concatenation with a string, PHP will parse the variable as a string:

      $my_int = 27;
      echo "Sammy" . $my_int;
      

      Output

      Sammy27

      You’ve covered the two main ways to concatenate, or combine, strings. Sometimes you may want to replace, or add to, the string completely. Next, let’s explore how PHP allows you to overwrite or update a string.

      Updating a String

      Normal variables in PHP are mutable, which means they can be changed or overwritten. Let’s explore what happens when you change the value for the $my_name variable:

      $my_name = "Sammy";
      echo $my_name . "n";
      $my_name = "Shark";
      echo $my_name;
      

      Output

      Sammy Shark

      First, the variable was set to "Sammy" and displayed using echo. Then it was set to "Shark", overwriting the variable, so that when echo was called a second time, it displayed the new value of "Shark".

      Instead of overwriting the variable, you can use the concatenating assignment operator .= to append to the end of a string:

      $my_name = "Sammy";
      $my_name .= " Shark";
      echo $my_name;
      

      First, you set the $my_name variable to "Sammy", then used the .= operator to add " Shark" to the end of it. The new value for $my_name is Sammy Shark.

      Output

      Sammy Shark

      To prepend to the beginning of a string, you would overwrite while using the original string:

      $my_name = "Shark";
      $my_name = "Sammy " . $my_name;
      echo $my_name;
      

      This time, you first set the $my_name variable to "Shark", then used the = operator to override the $my_name variable with the new string "Sammy ", combined with the previous value of the $my_name variable, which before being overridden is "Shark". The final value for $my_name is Sammy Shark.

      Output

      Sammy Shark

      Overwriting, appending, and prepending give us the ability to make changes and build the strings required for our applications.

      Whitespace in Strings

      Because PHP does not care about whitespace, you can put as many spaces or line breaks within your quotes as you would like.

      echo "Sammy
      The           (silly)
      Shark";
      

      TEXT Output

      Sammy The (silly) Shark

      Keep in mind that HTML renders whitespace differently. New lines require a <br> tag, so even though your source may have new lines, you will not see those new lines displayed on a web page. Similarly, no matter how many spaces there are in your code, only a single space is displayed between characters.

      HTML Output

      Sammy The (silly) Shark

      Clean and consistent use of whitespace is one of the best tools for making code more readable. Since PHP essentially ignores whitespace, you have a lot of flexibility that you can use to your advantage. An integrated development environment (IDE) can help you stay consistent with your code and use of whitespace.

      Conclusion

      Being able to control the way our strings are rendered is essential for communicating with an application’s end user. By updating and combining variables that include special characters, you can clearly communicate while keeping repetition to a minimum.

      As you continue to work with strings, keep in mind these three aspects:

      1. Pay special attention to quotes within your strings.
      2. Use concatenation to combine your strings.
      3. Use variables to make your strings reusable.

      If you would like to read more about PHP, check out the PHP topic page.



      Source link

      How To Work with the Box Model in CSS


      The author selected the Diversity in Tech Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The box model is the ruleset a browser uses to determine an element’s size and how it interacts with other elements. The contents of the HTML element, as well as several CSS properties, all contribute to the calculations a browser uses to turn HTML and CSS code into a final, rendered web page. Knowing how the box model works and how to manipulate it effectively can be the difference between a well-aligned design and a web page with unwanted horizontal scrolling and extra space between content. Understanding how the box model works will help you write CSS more efficiently and find solutions to rendering issues in the browser.

      Note: Most HTML elements fall in to one of two categories of boxes, an inline or a block. A <span> element is a generic inline element, as it stays inline with the text content. The <div> element, is a generic block element. This tutorial will focus on how the box model affects block elements, as it is the broadest use of the box model ruleset.

      Be aware that changes to the display property can result in changes to how the box model functions in ways outside of the goals of this tutorial, especially when working with tables, Flexbox, and CSS Grid.

      In this tutorial, you will use the margin, padding, border, width, and height properties, which are the primary properties the box model uses. You will also work with the box-sizing properties to understand how the box model can be changed. Lastly, you will use your browser’s developer tools to inspect the box model.

      Prerequisites

      In this section, you will set up the HTML base for use throughout the tutorial. You will also access your browser’s developer tools and begin to use them to help identify the properties that make up the box model.

      To start, open up index.html in your text editor and add the following HTML to the file:

      index.html

      <!doctype html>
      <html>
          <head>
              <title>Box Model</title>
              <link href="https://www.digitalocean.com/community/tutorials/styles.css" rel="stylesheet" />
          </head>
          <body>
          </body>
      </html>
      

      The HTML includes a reference to a styles.css file in the <link /> tag. Go ahead and create that file; you will begin to edit that in the next section.

      Next, you will need content to apply styles to and start to work with the box model. In the next code block, add the highlighted code within the <body> tag. Highlighted code like this will be used throughout the tutorial to identify changes and additions to the code. For the content, create two <div> elements and fill them with the following two quotes from Alice’s Adventures in Wonderland, by Lewis Carol:

      index.html

      ...
      <body>
          <div>
              Alice had begun to think that very few things indeed were really impossible.
          </div>
      
          <div>
              "Begin at the beginning," the King said gravely, "and go on till you come to the end: then stop."
          </div>
      </body>
      ...
      

      Next, open up index.html in your browser of choice and open the browser’s developer tools. This can often be accomplished by right-clicking on the page and selecting Inspect or Inspect Element. Once you have opened the developer tools, inspect the first <div> element. In both Firefox and Chrome a visual diagram of the box model will be visible. The following is what you would find in the Firefox developer tools:

      Diagram of the box model with defined boxes from the outer most to inner most as margin, border, and padding, all set to 0 with a computed width and height of 970 by 19.

      Looking closer at the box model visualization from Firefox, the properties that make up the box model are show from the center outward as width, height, padding, border, and margin. These five properties make up the box model and provide the dimensional characteristics of the element. As you work with each of the properties and refresh your changes in the browser, be sure to keep the developer tools open to reference this box model visualization of your elements.

      In this section, you set up your HTML for the tutorial, opened up your browser’s developer tools, and accessed the box model visualization guide. In the next section you will begin writing CSS for the border property, which will provide a beginning visual style of the box model for your <div> elements.

      Using the border Property to Visualize Containers

      Now that you have your HTML set up, you will begin applying the properties of the box model, beginning with the border property. In this section you will use the border property to create a visual outline of the <div> elements and see how the property affects the box model.

      The border property is what is known as a shorthand property, as it is a combination of three different properties: border-width, border-style, and border-color. Additionally, there are more border properties that allow for specifying sides, like border-right, which functions like border and is a shorthand combination of border-right-width, border-right-style, and border-right-color.

      border-width, border-style, and border-color also behave as shorthand for their border-top, border-right, border-bottom, and border-left counterparts and apply the styles clockwise from top to right, then bottom, and lastly the left side. For example, border-width: 10px 2px 8px 4px; would apply a 10px border to the top, a 2px border to the right, an 8px border to the bottom, and a 4px border to the left side of the box.

      Open styles.css in your text editor, write a type selector for the div element, and add the border property. For the value, the order is not critical, though a common ordering tends to be width, style, and color. With that in mind, set the value for the border property to 1px solid red:

      styles.css

      div {
          border: 1px solid red;
      }
      

      Save your changes to styles.css then open index.html in your browser. The content of the <div> elements will be wrapped tightly by a thin red line on the perimeter of the box. Between the two lines of text, there will be a thicker border. This occurs when borders from two different elements are set side-by-side, doubling the visual size of the border. The changes will look like this in your browser:

      Two wide rectangles each with text in a black serif font and a thin red border tight against the text.

      With index.html open in your browser, return to the browser developer tools and inspect one of the two <div> elements. Return to the view in the developer tools that shows the box model of the element. In the inner-most box is the width by height of the element, then the padding, and finally the border, noted to have 1 on each side of its box. See the following image from the Firefox developer tools:

      Diagram of the box model with defined boxes from the outer most to inner most as margin set to 0, border set to 1, padding set to 0, and a computed width and height of 970 by 19.

      With the Firefox window set at 986px wide, the width of the inner box of the box model diagram is 968 by 19, but following the diagram is another value that is 970 by 21. This is the computed width and height, which is the final pixel size the browser renders, combining height, width, border, and padding property values together. This difference in size is two more in either dimension, which coincides with the size the border adds to the height and width.

      In this section, you created a border on the <div> elements and saw how this one property affects the computed dimensions of those elements. In the next section, you will expand on your styles by applying inner spacing between the border and the text with the padding property.

      Using the padding Property to Create Space Inside the Container

      Your work with the border property in the previous section gave a visual boundary to the box, but it is very close to the text. Next you will use the padding property to add space on the interior of the box, providing room between the text and box’s border.

      Similar to the border property, the padding property is also a shorthand property. However, padding is shorthand only for the sides, such as the padding-bottom property. When a single value is used, the same value will be applied to all sides. For example, padding: 20px; applies a 20px padding to all sides. When two values are used, then the first value is applied to the top and bottom sides, while the second value is applied to the left and right. For instance, the following padding: 20px 40px; will apply 20px padding to the top and bottom of the box, while the 40px padding is on the left and right sides. This progresses to three values that follow top side, left and right sides, then the bottom. At four values each side is represented as top, right, bottom, and left.

      Open your styles.css file in your text editor and, after the border property, add a padding property with a value of 30px 60px. It is important to put a space between the values, as that is how CSS delineates between multiple values.

      styles.css

      div {
          border: 1px solid red;
          padding: 30px 60px;
      }
      

      Save the latest change to your styles.css file, then return to your index.html file in your browser and refresh the page. The two elements have grown in height and the positioning of the text within the red boxes has shifted down and to the right with extra space below the text. See the following image for what the browser is expected to render:

      Two wide rectangles each with text in a black serif font and a thin red border with space between the text and border.

      Once again, return to the browser developer tools and inspect one of the two boxes. The box model diagram now displays the padding with a 30 on the top and bottom and a 60 on the left and right of the box.

      Diagram of the box model with the padding area of the diagram showing a value of 30 for the top and bottom and a 60 for the left and right.

      You expanded on the complexities of the box model by using the padding property on the <div> elements to give visual space between the border and the text. The box model visual guide in your browser’s developer tools showcased these changes and their effects on the dimensional values displayed. Next you will work with the width and height properties to see how they further affect the box model and how these two properties are changed by the padding property.

      Using the width and height Properties to Limit the Dimension Width

      This section will focus on using defined width and height property values to enforce dimensions on the <div> elements and how those properties are treated in the box model. This section will use pixel units for the width and height values, which is often referred to as fixed dimensions, as well as percent units, which are called fluid dimensions. Unlike the previous two properties, width and height are not shorthand. These apply a defined value. However, setting dimension values with CSS causes a questionable effect that goes back to the early specifications of the language. The width and height are the set dimensions of the visible content before padding and border values are applied. This results in a box that is larger than expected.

      To try out this aspect of the box model, return to the styles.css file in your text editor and add the width property with a value of 250px:

      styles.css

      div {
          ...
          width: 250px;
      }
      

      Save your changes to styles.css, switch to your browser, and refresh index.html. When the page reloads, the content will be much more narrow and wrapped into multiple lines of text. See the following image for how this will appear in your browser:

      Two narrow rectangles each with text in a black serif font and a thin red border with space between the text and border.

      Open up the browser developer tools and inspect one of the two <div> elements. At the center of the box is the value defined by the width property with 250 by 57. However, as the image from the Firefox box model diagram shows, the full width of the element is not 250, but instead 372.

      Diagram of the box model with height and width values set in blue at the center of the box with a width of 250 and black sans-serif text below showing a total width of 372.

      The computed width is determined by the width, which sets the width of the content, followed by the size of the right and left padding values, then by the right and left border-width values. This construct of the box model was devised early in CSS’s development and requires developers to remember that the width and height properties define the dimensions of the content, not the box. This is the default behavior and understanding it as such will help debug problems in the future.

      Instead of using a fixed pixel value for the width, use a fluid percent for the width of 100%. By default, a <div> element extends the full width, but there is a difference here between extending the default full width and having a declared width value of 100%. In your styles.css, change 250px to 100%:

      styles.css

      div {
          ...
          width: 100%;
      }
      

      Save the styles.css file and refresh index.html in your browser. The <div> elements now extend past the viewport’s edge, no matter the size of the window. What is happening is the same as what happened with 250 becoming 372: The full width of the element is now 100% of the available width plus the 122 pixels created with the padding and border values.

      Return to your styles.css file and start by returning the width value to 250px. Next, add a height property and add a value you know will be smaller than the content height. 40px will be sufficient with this content:

      styles.css

      div {
          ...
          width: 250px;
          height: 40px;
      }
      

      Save these changes to the styles.css file and refresh index.html in your browser. The padding will now appear as though it is smaller on the bottom, when in fact the browser is being posed with a dilemma: The height is explicitly set, but the content is larger than the container. The rules the browser follows use the defined height value, and if there were longer content it would extend outside the box.

      With the browser developer tools open, inspect one of the <div> elements and the element will be highlighted in the rendered view. Hover over the padding area of the box model diagram to highlight the padding area of the element. The text content is going into the padding area. See the following image for what you will find in your browser:

      A box with black serif text and red thin border with the spacing between the text and border highlighted purple and the text going in to the bottom portion of the purple area.

      In situations where the content can be variable in length, it is best to avoid a defined height value and instead let the natural height of the content determine the height. Web browsers are built to grow downward and scroll vertically by default, making height the unpredictable and least controllable dimension.

      For this situation, it is best to remove the height attribute altogether. Return to styles.css in your text editor and remove the height property and its value from the file and save your changes. Removing the height value makes the height dependent on the amount of content inside the container. Your CSS will now look like the following:

      styles.css

      div {
        border: solid red 1px;
        padding: 30px 60px;
        width: 250px;
      } 
      

      In this section, you applied the width and height properties to the <div> elements. You discovered how the height property can be difficult to implement due to the flowing nature of web content. Lastly you learned how these dimension properties are applied to an element before the padding property, leading to a larger dimension than intended. Next, you will work with the spacing on the outside of the elements with the margin property.

      Using the margin Property to Create Space Outside the Container

      In this next, section you will use the margin property to apply spacing on the outside of the border to provide spacing between other boxes. The margin property functions similarly to the padding property, with the same long- and short-hand property variations. You will use margin to provide space between the two <div> elements on the page and find how margin differs from padding.

      To start, open styles.css in your text editor, add a margin property to the div type selector and give a value of 20px. This will apply a 20px space on each side of the <div> elements on the page:

      styles.css

      div {
          ...
          margin: 20px;
      }
      

      Save your changes to styles.css then open your browser and load or refresh your index.html file. You will find that the containers have moved to the right and down by 20 pixels. See the following image for what this will look like:

      Two boxes of black serif text with thin red borders with space between each box.

      Take a look at the spacing between the two <div> elements in your browser. The spacing between these is 20px and not 40px, even though there is margin on the bottom of the first <div> and a margin on the top of the second <div>. This is due to a feature of the margin property where adjacent containers overlap their margin properties, taking the value from the larger margin. This may not make sense at first, but it can be helpful to think of the box model as describing a physical object and then defining how much space you want around each one of those objects. For example, if you have 10 people and you want 2 meters of space around each person, the space from one person to the next will be 2 meters, not 4 meters.

      Since the largest margin value is taken as the outside spacing value, change the value of the property so the top and bottom are different. You can do this with the shorthand by making sure the first and third values in the list are different, or by using the margin-top and margin-bottom properties. Keep the top, right, and left values at 20px, but change the bottom value to be 60px.

      styles.css

      div {
          ...
          margin: 20px 20px 60px;
      }
      

      The first value in the shorthand list for a margin defines the top value, the second value defines the right and left, and the third defines the bottom value. Save your changes to styles.css and refresh index.html in your browser. There will now be much more space between the two containers as shown in the following image:

      Two boxes of black serif text with thin red borders with more space between each box.

      Now, inspect one of the two <div> elements with the browser developer tools. Unlike all the other properties, the margin values do not change the computed height or the width of the container:

      Diagram of the box model with margin set in yellow with the number 20 on the top, left, and right side of the box and the number 60 at the bottom.

      The margin property has two special features that padding does not. First, margin accepts negative values, meaning it can move closer to adjacent elements and cause them to overlap. Additionally, the margin property accepts a value of auto, which can be used for centering content. Due to how the browser defaults work, this auto value will only center content horizontally and only if a defined width property is less than 100% of the total available space.

      Return to the styles.css file in your text editor and change the second value of the margin property from 20px to auto:

      styles.css

      div {
          ...
          margin: 20px auto 60px;
      }
      

      Save this change to styles.css and reload index.html in your browser. The <div> containers will now appear horizontally centered, as in the next image:

      Two boxes of black serif text with thin red borders with space between each box centered to the page horizontally.

      You used the margin property in this section to add space between the quotes in the <div> elements. You changed the margin to show how it overlaps and defers to the largest of the adjacent values. Also, you set the value for the margin-left and margin-right properties to auto, which centered the containers. In the last section you will use the box-sizing property to change how the box model behaves and the properties relate to one another.

      Using the box-sizing Property to Change the Box Model Behavior

      In this final section, you will use the box-sizing property, which allows the box model to change how it is formulated. As you have worked with the box model, the width, height, padding, and border properties have contributed to the overall dimensions of the box model. Now with the box-sizing property, you will be able to have the padding and border calculated by the browser to enforce the values set to the width and height values.

      Up to this point, you have worked with the default state of the box-sizing property, which is content-box. The content-box box model determines the width dimension by adding the width, padding-right, padding-left, border-right-width, and border-left-width to be the final computed width value of the box. Likewise, the content-box finds the height dimension by adding the height, padding-top, padding-bottom, border-top-width, and border-bottom-width to arrive at the final computed height value for the box. As discussed in previous sections, this results in a larger than intended box that can disrupt layout and design.

      The alternative to the content-box value for the box-sizing property is border-box. Instead of adding padding and border properties to the declared width and height values to get the computed value, it subtracts the values. This means that the width of a box with a border-box box model is the width property minus the sum of the left and right padding values and the left and right border-width values. The result is a computed width equal to the width property value.

      Open styles.css in your text editor and add a box-sizing property with a value of border-box to the div type selector:

      styles.css

      div {
          ...
          box-sizing: border-box;
      }
      

      Return to your browser and reload index.html. The size of the containers will now be smaller, as the browser is now decreasing the box model’s width so that the computed width of width, padding, and border does not exceed the width value defined in the CSS file.

      Inspect one of the <div> elements with the browser developer tools to find how the box-sizing property has affected the box model. In the Firefox developer tools, width is defined as 128px, even though the width property in styles.css has a value of 250px. The computed value of the element is 250px, calculated by adding 128px plus 60px from the right padding, 60px from the left padding, 1px from the right border width, and 1px from the left border width. The Firefox developer tools box model is shown in the following image:

      Diagram of the box model set to border-box with margin set in yellow, border set in gray, padding set in purple, and the height and width set in blue.

      The box-sizing property can be changed on all elements of a web page by using the universal selector (*), also known as the star selector. This selector applies the styles to all elements on a page. This selector should be used with caution, since it does effect all elements and can potentially cause performance issues on pages that have a substantial amount of elements.

      Open styles.css and remove the box-sizing property from the div type selector. Then add a universal selector before the div selector with a box-sizing property set to border-box:

      styles.css

      * {
          box-sizing: border-box;
      }
      ...
      

      Save these changes to styles.css and reload index.html. You will find no difference visually. The responsibility of changing the box model has moved from an explicit setting to a universal setting.

      In this section, you used the box-sizing property to change how the box model behaves with the border-box value, creating a more comprehensive way of working with the box model. You also learned about the universal selector and how to apply the box-sizing property to all elements on a web page.

      Conclusion

      The box model is necessary to understand how styles are applied to elements and how styles affect the flow of content. In this tutorial, you learned how to use the border, padding, margin, height, and width properties and how they relate to each other in the box model. You used the default box model of the box-sizing property, which will help you plan and debug styling situations. Also, you learned about the border-box value that changes how the box model functions and allows for a more intuitive method of working with the box model. Remember that leaning into browser defaults helps maintain good performance, so changing the box model should be done as needed instead of universally.

      If you would like to read more CSS tutorials, try out the other tutorials in the How To Style HTML with CSS series.



      Source link

      How To Work with Files using the fs Module in Node.js


      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      Working with files is as common for development purposes as it is for non-development purposes. In daily computer use, a user would likely read and write data to files in various directories in order to accomplish tasks like saving a downloaded file or accessing data to be used in another application. In the same way, a back-end program or command line interface (CLI) tool might need to write downloaded data to a file in order to save it, or a data-intensive application may need to export to JSON, CSV, or Excel formats. These programs would need to communicate with the filesystem of the operating system on which they are running.

      With Node.js, you can programmatically manipulate files with the built-in fs module. The name is short for “file system,” and the module contains all the functions you need to read, write, and delete files on the local machine. This unique aspect of Node.js makes JavaScript a useful language for back-end and CLI tool programming.

      In this article, you will use the fs module to read a file created via the command line, create and write to a new file, delete the file that you created, and move the first file into a different folder. The fs module supports interacting with files synchronously, asynchronously, or via streams; this tutorial will focus on how to use the asynchronous, Promise-based API, the most commonly used method for Node.js developers.

      Prerequisites

      Step 1 — Reading Files with readFile()

      In this step, you’ll write a program to read files in Node.js. To do this, you’ll need to import the fs module, a standard Node.js module for working with files, and then use the module’s readFile() function. Your program will read the file, store its contents in a variable, then log its contents to the console.

      The first step will be to set up the coding environment for this activity and the ones in the later sections.

      Create a folder to store your code. In your terminal, make a folder called node-files:

      Change your working directory to the newly created folder with the cd command:

      In this folder, you’ll create two files. The first file will be a new file with content that your program will read later. The second file will be the Node.js module that reads the file.

      Create the file greetings.txt with the following command:

      • echo "hello, hola, bonjour, hallo" > greetings.txt

      The echo command prints its string argument to the terminal. You use > to redirect echo’s output to a new file, greetings.txt.

      Now, create and open readFile.js in your text editor of choice. This tutorial uses nano, a terminal text editor. You can open this file with nano like this:

      The code for this file can be broken up into three sections. First, you need to import the Node.js module that allows your program to work with files. In your text editor, type this code:

      node-files/readFile.js

      const fs = require('fs').promises;
      

      As mentioned earlier, you use the fs module to interact with the filesystem. Notice, though, that you are importing the .promises part of the module.

      When the fs module was first created, the primary way to write asynchronous code in Node.js was through callbacks. As promises grew in popularity, the Node.js team worked to support them in the fs module out of the box. In Node.js version 10, they created a promises object in the fs module that uses promises, while the main fs module continues to expose functions that use callbacks. In this program, you are importing the promise version of the module.

      Once the module is imported, you can create an asynchronous function to read the file. Asynchronous functions begin with the async keyword. With an asynchronous function, you can resolve promises using the await keyword, instead of chaining the promise with the .then() method.

      Create a new function readFile() that accepts one argument, a string called filePath. Your readFile() function will use the fs module to load the file into a variable using async/await syntax.

      Enter the following highlighted code:

      node-files/readFile.js

      const fs = require('fs').promises;
      
      async function readFile(filePath) {
        try {
          const data = await fs.readFile(filePath);
          console.log(data.toString());
        } catch (error) {
          console.error(`Got an error trying to read the file: ${error.message}`);
        }
      }
      

      You define the function with the async keyword so you can later use the accompanying await keyword. To capture errors in your asynchronous file reading operation, you enclose the call to fs.readFile() with a try...catch block. Within the try section, you load a file to a data variable with the fs.readFile() function. The only required argument for that function is the file path, which is given as a string.

      The fs.readFile() returns a buffer object by default. A buffer object can store any kind of file type. When you log the contents of the file, you convert those bytes into text by using the toString() method of the buffer object.

      If an error is caught, typically if the file is not found or the program does not have permission to read the file, you log the error you received in the console.

      Finally, call the function on the greetings.txt file with the following highlighted line:

      node-files/readFile.js

      const fs = require('fs').promises;
      
      async function readFile(filePath) {
        try {
          const data = await fs.readFile(filePath);
          console.log(data.toString());
        } catch (error) {
          console.error(`Got an error trying to read the file: ${error.message}`);
        }
      }
      
      readFile('greetings.txt');
      

      Be sure to save your contents. With nano, you can save and exit by pressing CTRL+X.

      Your program will now read the greetings.txt file you created earlier and log its contents to the terminal. Confirm this by executing your module with node:

      You will receive the following output:

      Output

      hello, hola, bonjour, hallo

      You’ve now read a file with the fs module’s readFile() function using the async/await syntax.

      Note: In some earlier versions of Node.js, you will receive the following warning when using the fs module:

      (node:13085) ExperimentalWarning: The fs.promises API is experimental
      

      The promises object of the fs module was introduced in Node.js version 10, so some earlier versions still call the module experimental. This warning was removed when the API became stable in version 12.6.

      Now that you’ve read a file with the fs module, you will next create a file and write text to it.

      Step 2 — Writing Files with writeFile()

      In this step, you will write files with the writeFile() function of the fs module. You will create a CSV file in Node.js that keeps track of a grocery bill. The first time you write the file, you will create the file and add the headers. The second time, you will append data to the file.

      Open a new file in your text editor:

      Begin your code by importing the fs module:

      node-files/writeFile.js

      const fs = require('fs').promises;
      

      You will continue to use async/await syntax as you create two functions. The first function will be to make the CSV file. The second function will be to add data to the CSV file.

      In your text editor, enter the following highlighted code:

      node-files/writeFile.js

      const fs = require('fs').promises;
      
      async function openFile() {
        try {
          const csvHeaders="name,quantity,price"
          await fs.writeFile('groceries.csv', csvHeaders);
        } catch (error) {
          console.error(`Got an error trying to write to a file: ${error.message}`);
        }
      }
      

      This asynchronous function first creates a csvHeaders variable that contains the column headings of your CSV file. You then use the writeFile() function of the fs module to create a file and write data to it. The first argument is the file path. As you provided just the file name, Node.js will create the file in the same directory that you’re executing the code in. The second argument is the data you are writing, in this case the csvHeaders variable.

      Next, create a new function to add items to your grocery list. Add the following highlighted function in your text editor:

      node-files/writeFile.js

      const fs = require('fs').promises;
      
      async function openFile() {
        try {
          const csvHeaders="name,quantity,price"
          await fs.writeFile('groceries.csv', csvHeaders);
        } catch (error) {
          console.error(`Got an error trying to write to a file: ${error.message}`);
        }
      }
      
      async function addGroceryItem(name, quantity, price) {
        try {
          const csvLine = `n${name},${quantity},${price}`
          await fs.writeFile('groceries.csv', csvLine, { flag: 'a' });
        } catch (error) {
          console.error(`Got an error trying to write to a file: ${error.message}`);
        }
      }
      

      The asynchronous addGroceryItem() function accepts three arguments: the name of the grocery item, the amount you are buying, and the price per unit. These arguments are used with template literal syntax to form the csvLine variable, which is the data you are writing to the file.

      You then use the writeFile() method as you did in the openFile() function. However, this time you have a third argument: a JavaScript object. This object has a flag key with the value a. Flags tell Node.js how to interact with the file on the system. By using the flag a, you are telling Node.js to append to the file, not overwrite it. If you don’t specify a flag, it defaults to w, which creates a new file if none exists or overwrites a file if it already exists. You can learn more about filesystem flags in the Node.js documentation.

      To complete your script, use these functions. Add the following highlighted lines at the end of the file:

      node-files/writeFile.js

      ...
      async function addGroceryItem(name, quantity, price) {
        try {
          const csvLine = `n${name},${quantity},${price}`
          await fs.writeFile('groceries.csv', csvLine, { flag: 'a' });
        } catch (error) {
          console.error(`Got an error trying to write to a file: ${error.message}`);
        }
      }
      
      (async function () {
        await openFile();
        await addGroceryItem('eggs', 12, 1.50);
        await addGroceryItem('nutella', 1, 4);
      })();
      

      To call the functions, you first create a wrapper function with async function. Since the await keyword can not be used from the global scope as of the writing of this tutorial, you must wrap the asynchronous functions in an async function. Notice that this function is anonymous, meaning it has no name to identify it.

      Your openFile() and addGroceryItem() functions are asynchronous functions. Without enclosing these calls in another function, you cannot guarantee the order of the content. The wrapper you created is defined with the async keyword. Within that function you order the function calls using the await keyword.

      Finally, the async function definition is enclosed in parentheses. These tell JavaScript that the code inside them is a function expression. The parentheses at the end of the function and before the semicolon are used to invoke the function immediately. This is called an Immediately-Invoked Function Expression (IIFE). By using an IIFE with an anonymous function, you can test that your code produces a CSV file with three lines: the column headers, a line for eggs, and the last line for nutella.

      Save and exit nano with CTRL+X.

      Now, run your code with the node command:

      There will be no output. However, a new file will exist in your current directory.

      Use the cat command to display the contents of groceries.csv:

      You will receive the following output:

      node-files/groceries.csv

      name,quantity,price
      eggs,12,1.5
      nutella,1,4
      

      Your call to openFile() created a new file and added the column headings for your CSV. The subsequent calls to addGroceryItem() then added your two lines of data.

      With the writeFile() function, you can create and edit files. Next, you will delete files, a common operation when you have temporary files or need to make space on a hard drive.

      In this step, you will delete files with the unlink() function in the fs module. You will write a Node.js script to delete the groceries.csv file that you created in the last section.

      In your terminal, create a new file for this Node.js module:

      Now you will write code that creates an asynchronous deleteFile() function. That function will accept a file path as an argument, passing it to the unlink() function to remove it from your filesystem.

      In your text editor, write the following code:

      node-files/deleteFile.js

      const fs = require('fs').promises;
      
      async function deleteFile(filePath) {
        try {
          await fs.unlink(filePath);
          console.log(`Deleted ${filePath}`);
        } catch (error) {
          console.error(`Got an error trying to delete the file: ${error.message}`);
        }
      }
      
      deleteFile('groceries.csv');
      

      The unlink() function accepts one argument: the file path of the file you want to be deleted.

      Warning: When you delete the file with the unlink() function, it is not sent to your recycle bin or trash can but permanently removed from your filesystem. This action is not reversible, so please be certain that you want to remove the file before executing your code.

      Exit nano, ensuring that you save the contents of the file by entering CTRL+X.

      Now, execute the program. Run the following command in your terminal:

      You will receive the following output:

      Output

      Deleted groceries.csv

      To confirm that the file no longer exists, use the ls command in your current directory:

      This command will display these files:

      Output

      deleteFile.js greetings.txt readFile.js writeFile.js

      You’ve now confirmed that your file was deleted with the unlink() function.

      So far you’ve learned how to read, write, edit, and delete files. The following section uses a function to move files to different folders. After learning that function, you will be able to do the most critical file management tasks in Node.js.

      Step 4 — Moving Files with rename()

      Folders are used to organize files, so being able to programmatically move files from one folder to another makes file management easier. You can move files in Node.js with the rename() function. In this step, you’ll move a copy of the greetings.txt file into a new folder.

      Before you can code your Node.js module, you need to set a few things up. Begin by creating a folder that you’ll be moving your file into. In your terminal, create a test-data folder in your current directory:

      Now, copy the greetings.txt file that was used in the first step using the cp command:

      • cp greetings.txt greetings-2.txt

      Finish the setup by opening a JavaScript file to contain your code:

      In your Node.js module, you’ll create a function called moveFile() that calls the rename() function. When using the rename() function, you need to provide the file path of the original file and the path of the destination location. For this example, you’ll use a moveFile() function to move the greetings-2.txt file into the test-data folder. You’ll also change its name to salutations.txt.

      Enter the following code in your open text editor:

      node-files/moveFile.js

      const fs = require('fs').promises;
      
      async function moveFile(source, destination) {
        try {
          await fs.rename(source, destination);
          console.log(`Moved file from ${source} to ${destination}`);
        } catch (error) {
          console.error(`Got an error trying to move the file: ${error.message}`);
        }
      }
      
      moveFile('greetings-2.txt', 'test-data/salutations.txt');
      

      As mentioned earlier, the rename() function takes two arguments: the source and destination file paths. This function can move files to other folders, rename a file in its current directory, or move and rename at the same time. In your code, you are moving and renaming your file.

      Save and exit nano by pressing CTRL+X.

      Next, execute this program with node. Enter this command to run the program:

      You will receive this output:

      Output

      Moved file from greetings-2.txt to test-data/salutations.txt

      To confirm that the file no longer exists in your current directory, you can use the ls command:

      This command will display these files and folder:

      Output

      deleteFile.js greetings.txt moveFile.js readFile.js test-data writeFile.js

      You can now use ls to list the files in the test-data subfolder:

      Your moved file will appear in the output:

      Output

      salutations.txt

      You have now used the rename() function to move a file from your current directory into a subfolder. You also renamed the file with the same function call.

      Conclusion

      In this article, you learned various functions to manage files with Node.js. You first loaded the contents of a file with readFile(). You then created new files and appended data to an existing file with the writeFile() function. You permanently removed a file with the unlink() function, and then move and renamed a file with rename().

      Working with files programmatically is an important function of Node.js. Programs might need to output files for a user to use, or may need to store data for an application that is not always running. With the fs module’s functions, developers have control of how files are used in our Node.js programs.

      To learn more about the fs module, you can read the Node.js documentation. If you’d like to continue learning Node.js, you can return to the How To Code in Node.js series, or browse programming projects and setups on our Node topic page.



      Source link