Jörg Krause

Programming Web Applications with Node, Express and Pug

Jörg Krause

Berlin, Germany

Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com . For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/ . Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter.

ISBN 978-1-4842-2510-3

e-ISBN 978-1-4842-2511-0

DOI 10.1007/978-1-4842-2511-0

Library of Congress Control Number: 2016961762

© Jörg Krause 2017

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Printed on acid-free paper

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

Foreword

Node.js is one of the most fascinating software environments of recent years. Today it’s in version v6.x, a quite mature version. There are two lines: one with Long Term Support (LTS) currently in version 4.x, and the one with the most recent features in version 6.x. The version 6.x has updates quite often, sometimes weekly.

It’s necessary to have a well-known language to create web applications instead of inventing just another language all the time. Think of the history of Perl, PHP, Java, Ruby, C in all it derivates, and many more. The final answer might be JavaScript.

The foundation of JavaScript on the server is the V8 engine from Chrome browser that has been extracted and made available as an executable. And it is available on all platforms, finally.

For developers with a strong background in traditional object-oriented languages such as C# or Java, it might sound odd that JavaScript has such a tremendous impact and success. It’s a weird mixture of a very simple language and a very rich and quickly expanding ecosystem.

This Book

All codes from the book are available on Github for easy testing and download.

The book is very focused on the first steps and easy examples. There is almost no advanced code and the reference parts contain only those functions required to execute a web application. The purpose is to have all this information handy in one place instead of flipping through hundreds of online sources.

The combination of Node, Express, and Pug is well-tested and the versions used here work together smoothly. There s no support for other software modules and other version combinations.

Who Should Read This Book?

This book is aimed at beginners and web developers who are new to the web world. Node serves mainly the back-end developer. Maybe you are also a web designer, who discovered Node as an excellent way to upgrade your web pages with dynamic elements.

In any case, I tried not to ask any prerequisites or conditions of the reader. You do not need to be a computer scientist, nor in perfect command of language. You don’t need to know rocket science. No matter what context you have encountered on Jade, you will be able to read this text.

A435076_1_En_BookFrontmatter_Figc_HTML.jpg What You Need

In order to understand all examples, you need a working environment for creating web pages. That can be a Windows, a Linux, or even a Mac. It’s possible to use any text editor to get the stuff running, but I recommend you use one with a little support while typing the stuff. Check editors such as Visual Studio Code or Sublime Text.

If you have accidentally found this text and cannot do anything with the term “Bootstrap,” read it anyway. You will be learning one of the most modern techniques of web development, and the future belongs to the circle of excellent developers who can be build good-looking and device-independent sites.

Examples

You can find the sample project to this book on Github:

As You Read This Text

I will not dictate how you should read this text. In the first draft of the structure, I have tried several variations and found that there exists no ideal form. However, readers tend today to consume smaller chunks, independent chapters, and focused content. This book addresses this trend by reducing content to small, focused chunks, with no extraneous material.

Beginners should read the text as a narrative from the first to the last page. Those who are already somewhat familiar can safely skip certain sections.

Conventions Used in the Book

The theme is not technically easy to master, because scripts are often too extensive and it would be nice if you could support the best optical reading form. I have therefore included extra line breaks used to aid readability.

In general, each program code is set to a non-proportional font. In addition, scripts have line numbers:

1                                           function                    send(){                  
2         // do some stuff here
3   }

If you find you need to enter something in the prompt or in a dialog box, this part of the statement is in bold:

$ bower install bootstrap

The first character is the prompt and is not entered. I use the Linux prompt and the bash shell in the book. The commands will work, without any exception, unchanged even on Windows. The only difference then is the command prompt C:> or something similar at the beginning of the line. Usually the instructions are related to relative paths or no paths at all, so the actual prompt shouldn’t matter despite the fact that you will be in your working folder.

Expressions and command lines are sometimes peppered with all types of characters, and in almost all cases, it depends on each character. Often, I’ll discuss the use of certain characters in precisely such an expression, then the “important” characters with line breaks alone, and also—in this case—line numbers. Line numbers are used to reference the affected symbol in the text exactly (note the : character in line 2):

1   a.test {                    
2     :hover {
3       color: red
4     }
5   }

The font is non-proportional, so that the characters are countable and opening and closing parentheses are always among themselves.

Symbols

To facilitate the orientation in the search for a solution, there is a whole range of symbols that are used in the text.

A435076_1_En_BookFrontmatter_Figd_HTML.jpg Tip

This is a tip.

A435076_1_En_BookFrontmatter_Fige_HTML.jpg Information

This is an information.

A435076_1_En_BookFrontmatter_Figf_HTML.jpg Warning

This is a warning.

There are no questionnaires, exercises, or self-tests. It’s just a reference, an easy-to-read text to get you on your way.

Introduction

Node.js is a programming environment based on JavaScript. It’s mainly used for web application development, but not restricted to same. In conjunction with the Node Package Manager (npm), it provides a powerful environment to create platform-independent applications.

This book shows the basic parts you need to create a web application. Apart from Node itself, this includes the middleware framework Express and the template language Pug (formerly known as JADE).

The content presents Node in its elementary form, shows the programming of a simple web application, and explains the major modules. In the same style, Express and Pug are explained. The client does not have any particular role in this book. The pages served by the examples are plain HTML.

Contents

  1. Chapter 1:​ Installation Problems
    1. Node.​Js
    2. Problems with NPM
      1. Proxy
      2. SSL
    3. Problems with Git
      1. Proxy
      2. Git protocols
    4. Online installation
      1. Preparation
      2. Hard cases
      3. Installing NpmBox
      4. Installing Packages
  2. Chapter 2:​ The Components of an Application
    1. The Package Manager
    2. Libraries and Frameworks
      1. Basis Libraries of the Server
      2. Client Page Libraries
      3. Unit Tests
    3. Principles
      1. Web Apps
      2. Web sites
      3. Stateless HTML
      4. The User Experience
    4. Summary
  3. Chapter 3:​ Introduction to Node
    1. Elementary in JavaScript
    2. Installation and Configuration
      1. Configuration in package.​json
    3. Initialize the Node Application
      1. Approach under Linux
      2. Start a Node Application
    4. The first Application
    5. Packages
      1. Install Packages
    6. Provide a Server Application
      1. The simplest Server
      2. A Server with Express
    7. Handling Requests
      1. Introduction to Routing
      2. Architecture of the Application
    8. Synchronous and Asynchronous Calls
      1. Dynamic HTML
      2. Sending HTML Files
      3. Restriction of Verbs
      4. Handling Form Data
      5. Handling Querystring
    9. The complete Application
      1. The Application server.js
      2. The Starting Script start.js
      3. The Routing Functions router.js
      4. The Business Logic handler.js
      5. Template of the HTML Page home.html
    10. Summary
  4. Chapter 4:​ The Most Important Node Modules
    1. Global Modules
      1. Timer
      2. Global Objects
    2. HTTP and HTTPS
      1. Basics
      2. Fields
      3. Methods
      4. Classes
      5. Class http.​ClientRequest
      6. HTTPS
    3. Handling Files and Paths
      1. Access to the File System
      2. Functions for the File Access
      3. Functions for handling Streams
  5. Chapter 5:​ Introduction to Express
    1. Installation
    2. Application structure
      1. The express generator
      2. LESS or SASS
    3. Routing in Node application
      1. Routing in Express
      2. The Express Router
    4. An example application
      1. Middleware – the mediator layer
      2. Basic routes
      3. The Router Middleware (router.​use())
      4. Structure Routes
      5. Routes with Parameters (/​hello/​:​id)
      6. Router Middleware for Parameters (.​param)
      7. Several Routes (app.​route())
  6. Chapter 6:​ Introduction to Pug
    1. Overview
      1. Preparation
    2. Application structure
    3. Pug views
      1. Handling Partial Views
      2. Handling Layout Pages
      3. npm start
  7. Chapter 7:​ Language Components of Pug
    1. Doctype
      1. Short Spellings
      2. Own Doctypes
      3. Options
    2. Attributes
      1. Not coded Attribute
      2. Logical Attributes
      3. Style Attributes
      4. &​ Attributes
    3. Handling CSS Classes
      1. The Class Attribute
    4. The Class Literal
    5. ID Literal
    6. Instructions
      1. Definition by Cases (case)
      2. Conditions (if)
      3. Iterations
    7. JavaScript Code
      1. Unbuffered Codes
      2. Buffered Codes
      3. Buffered and not coded Codes
      4. Unbuffered Codes
      5. Buffered Code
      6. Buffered and not coded Codes
    8. Comments
      1. Comment Blocks
      2. Caused Comments
    9. Inherit from Templates
      1. Detail for inherting Templates
      2. Prepend and append Content Blocks
    10. Filter
    11. Partial Pages
      1. Merge Text
      2. Combination of Filters and Partial Pages
    12. Interpolations
      1. Coded Character String Interpolation
      2. Not Coded String Interpolation
      3. Tag Interpolation
    13. Mixins (Functions)
      1. Mixin Blocks
      2. Mixin Attributes
      3. Further Arguments
    14. Handling Text
      1. Connect Text
      2. Inline in Tag
      3. Block in Tag
      4. Handling Tags
      5. Extension of Blocks
      6. Self-Closing Tags
  8. Chapter 8:​ The Pug Command Line
    1. Installing the Command Line
    2. Use and Options
      1. Sample Applications for the Command Line
  9. Appendix
  10. Configuration of the file package.json
  11. Meaning of the Configuration Elements
  12. description
  13. The Default Values
  14. Brief description
  15. Reference Node.js Modules
  16. HTTP
  17. Global
  18. Console
  19. Timer
  20. Module
  21. Process
  22. ChildProcess
  23. Util
  24. Events
  25. Stream
  26. File System
  27. Path
  28. URL
  29. Querystring
  30. Assert
  31. OS
  32. Buffer
  33. The API Reference for Express
  34. Das Basic Objekt
  35. The application
  36. Request–The Request Object
  37. Methods
  38. Response–The Answer Object
  39. The API of the Router
  40. The Router in Detail
  41. Methods
  42. Further libraries
  43. Namespace Based Routing
  44. Resource-Based Routing
  45. The Pug API
  46. API Options
  47. API Functions
  48. Index

About the Author

A435076_1_En_BookFrontmatter_Figb_HTML.jpg

Jörg Krause has been working with software and software technology since the early 1980’s, beginning with a ZX 81 and taking his first steps as a programmer in BASIC and assembly language. He studied Information Technology at Humboldt University, Berlin but left early, in the 90’s, to start his own company. He has worked with Internet Technology and software development since the early days when CompuServe and FidoNet dominated. He’s been with Microsoft technologies and software since Windows 95.

In 1998, he worked on one of the first commercial e-commerce solutions, and wrote his first book in Germany, E-Commerce and Online Marketing , published by Carl Hanser Verlag, Munich. Due to its wide success, he started working as a freelance consultant and author in order to share his experience and knowledge with others. He has written several books for Apress, Hanser, Addison Wesley and other major publishers along with several self-published books—a total of over sixty titles. He also publishes articles in magazines and speaks at major conferences in Germany. Currently, Jörg works as an independent consultant, software developer, and author in Berlin, Germany.

In his occasional spare time, Jörg enjoys reading thrillers and science fiction novels, and going on a round of golf.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.216