recursal/MDN huggingface dataset:
Server-side website programming first steps
===========================================

In this module, we answer a few fundamental questions about server-side programming such as "What is it?", "How does it differ from client-side programming?", and "Why is it so useful?". We also provide an overview of some of the most popular server-side web frameworks, along with guidance on how to select the most suitable framework for creating your first project. Finally, we provide a high-level introductory article about web server security.

Prerequisites
-------------

Before starting this module, you don't need to have any knowledge of server-side website programming or any other type of programming.

However, you should understand something about the workings of websites and web servers. For that purpose, this is our recommended reading:

* What is a web server?
* What software do I need to build a website?
* How do you upload files to a web server?

With the basic understanding that you gain from this preparation, you'll be ready to work your way through the modules in this section.

Guides
------

Introduction to the server-side

Welcome to the MDN beginner's server-side programming course! The first article examines server-side programming from a high level, answering questions such as "What is it?", "How does it differ from client-side programming?", and "Why it is so useful?". After reading this, you will understand the additional capabilities available to websites through server-side coding.

Client-Server overview

Now that you know the purpose and potential benefits of server-side programming, we're going to examine what happens when a server receives a "dynamic request" from a browser. As most websites' server-side code handles requests and responses in a similar way, this will help you understand what you need to do when writing your own code.

Server-side web frameworks

The previous article explained what a server-side web application needs to do to respond to web browser requests. This article explains how web frameworks can simplify these tasks, and helps you choose the right framework for your first server-side web application.

Website security

Website security requires vigilance in all aspects of building and operating a site. This introductory article helps you understand the first important steps you can take to protect your web application against the most common threats.


**Note:** This topic deals with server-side frameworks, and how to use them to create websites. If you are looking for information on client-side JavaScript frameworks, see Understanding client-side JavaScript frameworks.

Assessments
-----------

This "first steps" module doesn't have any assessment because we haven't yet shown you any code. At this point, you should have a general understanding of the functionality you can deliver with server-side programming, and you have made a decision about what server-side web framework you will use to create your first server-side application.
Author detail page
==================

The author detail page needs to display the information about the specified `Author`, identified using their (automatically generated) `_id` field value, along with a list of all the `Book` objects associated with that `Author`.

Controller
----------

Open **/controllers/authorController.js**.

Add the following lines to the top of the file to `require()` the `Book` module needed by the author detail page (other modules such as "express-async-handler" should already be present).


```js
const Book = require("../models/book");
```


Find the exported `author_detail()` controller method and replace it with the following code.


```js
// Display detail page for a specific Author.
exports.author_detail = asyncHandler(async (req, res, next) => {
  // Get details of author and all their books (in parallel)
  const [author, allBooksByAuthor] = await Promise.all([
    Author.findById(req.params.id).exec(),
    Book.find({ author: req.params.id }, "title summary").exec(),
  ]);

  if (author === null) {
    // No results.
    const err = new Error("Author not found");
    err.status = 404;
    return next(err);
  }

  res.render("author\_detail", {
    title: "Author Detail",
    author: author,
    author\_books: allBooksByAuthor,
  });
});
```


 The approach is exactly the same as described for the Genre detail page.
 The route controller function uses `Promise.all()` to query the specified `Author` and their associated `Book` instances in parallel.
 If no matching author is found an Error object is sent to the Express error handling middleware.
 If the author is found then the retrieved database information is rendered using the "author\_detail" template.

View
----

Create **/views/author\_detail.pug** and copy in the following text.


```pug
extends layout

block content

  h1 Author: #{author.name}
  p #{author.date\_of\_birth} - #{author.date\_of\_death}

  div(style='margin-left:20px;margin-top:20px')

    h4 Books
    if author\_books.length
      dl
        each book in author\_books
          dt
            a(href=book.url) #{book.title}
          dd #{book.summary}
    else
      p This author has no books.
```


Everything in this template has been demonstrated in previous sections.

What does it look like?
-----------------------

Run the application and open your browser to `http://localhost:3000/`. Select the *All Authors* link, then select one of the authors. If everything is set up correctly, your site should look something like the following screenshot.

![Author Detail Page - Express Local Library site](/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Author_detail_page/locallibary_express_author_detail.png)

**Note:** The appearance of the author *lifespan* dates is ugly! We'll address that in the final challenge in this article.

Next steps
----------

* Return to Express Tutorial Part 5: Displaying library data.
* Proceed to final subarticle of part 5 : BookInstance detail page and challenge.
Date formatting using luxon
===========================

The default rendering of dates from our models is very ugly: *Mon Apr 10 2020 15:49:58 GMT+1100 (AUS Eastern Daylight Time)*. In this section we'll show how you can update the *BookInstance List* page from the previous section to present the `due_date` field in a more friendly format: Apr 10th, 2023.

The approach we will use is to create a virtual property in our `BookInstance` model that returns the formatted date. We'll do the actual formatting using luxon, a powerful, modern, and friendly library for parsing, validating, manipulating, formatting and localising dates.

**Note:** It is possible to use *luxon* to format the strings directly in our Pug templates, or we could format the string in a number of other places. Using a virtual property allows us to get the formatted date in exactly the same way as we get the `due_date` currently.

Install luxon
-------------

Enter the following command in the root of the project:


```bash
npm install luxon
```

Create the virtual property
---------------------------

1. Open **./models/bookinstance.js**.
2. At the top of the page, import *luxon*.

```js
const { DateTime } = require("luxon");
```


Add the virtual property `due_back_formatted` just after the URL property.


```js
BookInstanceSchema.virtual("due\_back\_formatted").get(function () {
  return DateTime.fromJSDate(this.due_back).toLocaleString(DateTime.DATE\_MED);
});
```


**Note:** Luxon can import strings in many formats and export to both predefined and free-form formats. In this case we use `fromJSDate()` to import a JavaScript date string and `toLocaleString()` to output the date in `DATE_MED` format in English: Apr 10th, 2023.
 For information about other formats and date string internationalization see the Luxon documentation on formatting.


Update the view
---------------

Open **/views/bookinstance\_list.pug** and replace `due_back` with `due_back_formatted`.


```pug
      if val.status != 'Available'
        //span (Due: #{val.due\_back} )
        span  (Due: #{val.due\_back\_formatted} )
```


That's it. If you go to *All book-instances* in the sidebar, you should now see all the due dates are far more attractive!

Next steps
----------

* Return to Express Tutorial Part 5: Displaying library data.
* Proceed to the next subarticle of part 5: Author list page and Genre list page challenge.
Test your skills: Styling basics
================================

The aim of this skill test is to assess whether you've understood our Styling web forms article.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

Styling basics 1
----------------

Our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. But your CSS should aim to fulfill the following requirements:

1. Add some kind of lightweight "reset" to make fonts, padding, margin, and sizing more consistent to begin with.
2. On top of that, add in some nice, consistent styling for the inputs and button.
3. Use some kind of layout technique to make the inputs and labels line up neatly.

Download the starting point for this task to work in your own editor or in an online editor.
Test your skills: HTML5 controls
================================

The aim of this skill test is to assess whether you've understood our The HTML5 input types article.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

HTML controls 1
---------------

First, let's explore some input types. Create appropriate inputs for a user to update their details for:

1. Email
2. Website
3. Phone number
4. Favorite color

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

HTML controls 2
---------------

Next, we want you to implement a slider control to allow the user to choose a maximum number of people to invite to their party.

1. Implement a basic slider control to go along with the provided label.
2. Give it a minimum value of 1, maximum value of 30, initial value of 10 and element `id` of `max-invite`.
3. Create a corresponding output element to put the current value of the slider into. Give it a class of `invite-output`, and semantically associate it with the input. If you do this correctly, the JavaScript included on the page will automatically update the output value when the slider is moved.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Basic controls
================================

The aim of this skill test is to assess whether you've understood our Basic native form controls article.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

Basic controls 1
----------------

This task starts you off nice and gently by asking you to create two `<input>` elements, for a user's ID and password, along with a submit button.

1. Create appropriate inputs for user ID and password.
2. You should also associate them with their text labels semantically.
3. Create a submit button inside the remaining list item, with button text of "Log in".

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Basic controls 2
----------------

The next task requires you to create working sets of checkboxes and radio buttons, from the provided text labels.

1. Turn the first `<fieldset>`'s contents into a set of radio buttons — you should only be able to select one pony character at once.
2. Make it so that the first radio button is selected upon page load.
3. Turn the second `<fieldset>`'s content into a set of checkboxes.
4. Add a couple more hotdog choices of your own.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.

Basic controls 3
----------------

The final task in this set requires you to create a file picker.

1. Create a basic file picker.
2. Allow the user to pick multiple files at once.
3. Allow the file picker to accept JPG and PNG images only.

Try updating the live code below to recreate the finished example:

Download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Form structure
================================

The aim of this skill test is to assess whether you've understood our How to structure a web form article.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

Form structure 1
----------------

In this task we want you to structure the provided form features:

1. Separate out the first two and second two form fields into two distinct containers, each with a descriptive legend (use "Personal details" for the first two, and "Comment information" for the second two).
2. Mark up each text label with an appropriate element so that it is semantically associated with its respective form field.
3. Add a suitable set of structural elements around the label/field pairs to separate them out.

Download the starting point for this task to work in your own editor or in an online editor.
Test your skills: Other controls
================================

The aim of this skill test is to assess whether you've understood our Other form controls article.

**Note:** You can try solutions in the interactive editors on this page or in an online editor such as CodePen, JSFiddle, or Glitch.

If you get stuck, you can reach out to us in one of our communication channels.

Other controls 1
----------------

In our first "other controls" assessment, we'll get you to create a multi-line text input.

1. Create a basic multi-line text input.
2. Associate it semantically with the provided "Comment" label.
3. Give the input 35 columns, and 10 rows of space in which to add comments.
4. Give the comments a maximum length of 100 characters.

To create the input, update the HTML code in the editor below:

Download the starting point for this task to work in your own editor or in an online editor.

Other controls 2
----------------

Now it's time to have a go at implementing a drop-down select menu, to allow a user to pick their favorite food from the choices provided.

1. Create your basic select box structure.
2. Associate it semantically with the provided "food" label.
3. Inside the list, split the choices up into 2 subgroups — "mains" and "snacks".

To create the menu, update the HTML code in the editor below:

Download the starting point for this task to work in your own editor or in an online editor.

Other controls 3
----------------

In our final task of this set, we start with much the same list of food choices. However, this time we want to do things differently:

1. Create a basic text input that is semantically associated with the provided label.
2. Put the food choices into a list that can be associated with a form input.
3. Associate the list with your text input, so that when you type characters, any of the list options that match the character sequence are given in a dropdown list as autocomplete suggestions.

To create the input, update the HTML code in the editor below:

Download the starting point for this task to work in your own editor or in an online editor.
Tools for game development
==========================

On this page, you can find links to our game development tools articles, which eventually aim to cover frameworks, compilers, and debugging tools.

asm.js

asm.js is a very limited subset of the JavaScript language, which can be significantly optimized and run in an ahead-of-time (AOT) compiling engine for much faster performance than your typical JavaScript performance. This is, of course, great for games.

Emscripten

An LLVM to JavaScript compiler; with Emscripten, you can compile C++ and other languages that can compile to LLVM bytecode into high-performance JavaScript. This is an excellent tool for porting applications to the Web! There is a useful Emscripten tutorial available on the wiki.

Firefox Profiler

The Firefox Profiler lets you profile your code to help figure out where your performance issues are so that you can make your game run at top speed.

Toolchain for developing and debugging games

How does this differ from normal web app debugging? What specialist tools are available? A lot of this is going to be covered by Will in tools, but here we should provide a kind of practical toolchain tutorial for debugging games, with links to Will's stuff:

* Basic tools overview
* Shader editor
* Performance tools (still in production, estimated early 2014)
Publishing games
================

HTML games have a huge advantage over native in terms of publishing and distribution — you have the freedom of distribution, promotion and monetization of your game on the Web, rather than each version being locked into a single store controlled by one company. You can benefit from the web being truly multiplatform. This series of articles looks at the options you have when you want to publish and distribute your game, and earn something out of it while you wait for it to become famous.

Game distribution
-----------------

So you've followed a tutorial or two and created an HTML game — that's great! Game distribution provides all you need to know about the ways you can distribute your newly created game into the wild — including hosting it yourself online, submitting it to open marketplaces, and submitting it to closed ones like Google Play or the iOS App Store.

Game promotion
--------------

Developing and finishing the game is not enough. You have to let the world know that you have made something interesting available, which people will enjoy playing. There are many Game promotion techniques — many of them free — so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game. Promoting the game helps a lot in monetizing it later on too, so it's important to do it effectively.

Game monetization
-----------------

When you spend your time building, publishing and promoting your game, you will at some point consider earning money out of it. Game monetization is essential to anyone who considers their game development work a serious endeavour on the path to becoming an independent game developer able to make a living, so read on and see what your options are. The technology is mature enough; it's just a matter of choosing the right approach.
Introduction to HTML Game Development
=====================================

Advantages
----------

1. Games built with HTML work on smartphones, tablets, PCs and Smart TVs.
2. Advertise and promote your game all over the Web as well as other media.
3. Payments. Charge what you want and use whatever payment processing service you like.
4. Update your game whenever you want.
5. Collect your own analytics!
6. Connect with your customers more closely,
7. Players can play the game anywhere, anytime.
Web Technologies
----------------

Web technologies in game development and their function| **Function** | **Technology** |
| --- | --- |
| **Audio** | Web Audio API |
| **Graphics** | WebGL (OpenGL ES
 2.0)
  |
| **Input** | Touch events,
 Gamepad API, device sensors, WebRTC,
 Full Screen API,
 Pointer Lock API |
| **Language** | JavaScript (or C/C++ using
 Emscripten to
 compile to JavaScript)
  |
| **Networking** | WebRTC and/or
 WebSockets |
| **Storage** | IndexedDB or the "cloud" |
| **Web** | HTML,
 CSS,
 SVG (and much more!)
  |

Fetch API

Send and receive any kind of data you want from a Web server like downloading new game levels and artwork to transmitting non-real-time game status information back and forth.

Full Screen API

Full screen gameplay.

Gamepad API

Use gamepads or other game controllers.

HTML and CSS

Build, style, and lay out your game's user interface.

HTML audio

Easily play simple sound effects and music.

IndexedDB

Store user data on their own computer or device.

JavaScript

 Fast web programming language to write the code for your game.
 To easily port your existing games Emscripten or Asm.js

Pointer Lock API

Lock the mouse or other pointing device within your game's interface.

SVG (Scalable Vector Graphics)

Build vector graphics that scale smoothly regardless of the size or resolution of the user's display.

Typed Arrays

Access raw binary data from within JavaScript; Manipulate GL textures, game data, or anything else.

Web Audio API

Control the playback, synthesis, and manipulation of audio in real time.

WebGL

Create high-performance, hardware-accelerated 3D (and 2D) graphics. OpenGL ES 2.0.

WebRTC

Real-Time Communications to control audio and video data, including teleconferencing and transmitting other application data back and forth between two users like chat.

WebSockets

Connect your app or site to a server to transmit data back and forth in real-time. Perfect for multiplayer gaming action, chat services, and so forth.

Web Workers

Spawn background threads running their own JavaScript code for multicore processors.
Tutorials
=========

This page contains multiple tutorial series that highlight different workflows for effectively creating different types of web games.

2D breakout game using pure JavaScript

In this step-by-step tutorial you'll implement a simple breakout clone using pure JavaScript. Along the way you will learn the basics of using the `<canvas>` element to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, and winning and losing states.

2D breakout game using Phaser

In this step-by-step tutorial you'll implement the same breakout clone as the previous tutorial series, except that this time you'll do it using the Phaser HTML game framework. This idea here is to teach some of the fundamentals (and advantages) of working with frameworks, along with fundamental game mechanics.

2D maze game with device orientation

This tutorial shows how to create a 2D maze game using HTML, incorporating fundamentals such as collision detection and sprite placement on a `<canvas>`. This is a mobile game that uses the Device Orientation and Vibration **APIs** to enhance the gameplay and is built using the Phaser framework.

2D platform game with Phaser

This tutorial series shows how to create a simple platform game using Phaser, covering fundamentals such as sprites, collisions, physics, collectables, and more.