├── .prettierrc ├── .vscode └── settings.json ├── lessons ├── images │ ├── me.jpg │ ├── zdnet.jpg │ ├── Expressjs.png │ ├── breakpoint.jpg │ ├── contacts.jpeg │ ├── dockerhub.jpg │ ├── node-deno.png │ ├── node-logo.png │ ├── chrome-debug.jpg │ ├── deno-deployed.jpg │ ├── deno-object.jpg │ ├── deno-styled.jpg │ ├── dockerhub-web.jpg │ ├── edge-inspect.jpg │ ├── express-app.jpg │ ├── image-latest.jpg │ ├── tagged-image.jpg │ ├── what-i-know.png │ ├── cosmos-options.jpg │ ├── default-oak-app.jpg │ ├── deno-extension.jpg │ ├── deno-info-path.jpg │ ├── deno-templates.jpg │ ├── export-default.jpg │ ├── oak-default-app.jpg │ ├── options-options.jpg │ ├── simple-oak-app.jpg │ ├── app-with-templates.jpg │ ├── chrome-hover-args.jpg │ ├── default-hostname.jpg │ ├── deno-intellisense.jpg │ ├── handlebars-readme.jpg │ ├── registry-provider.jpg │ ├── simple-web-server.jpg │ ├── static-site-deps.jpg │ ├── stdlib-typescript.jpg │ ├── FrontendMastersLogo.png │ ├── always-in-workspace.jpg │ ├── default-express-app.jpg │ ├── denoexercises-image.jpg │ ├── exercise-dockerfile.jpg │ ├── integrated-terminal.jpg │ ├── deno-vs-node-benchmarks.jpg │ └── logo.svg ├── permissions │ ├── permission-specificity.md │ ├── determining-permissions.md │ ├── requesting-permission.md │ └── granting-permissions.md ├── dependencies │ ├── compatiblity-with-node.md │ ├── think-like-a-browser.md │ ├── best-practices.md │ ├── local-dependencies.md │ └── remote-dependencies.md ├── welcome │ ├── exercises.md │ └── intro.md ├── webserver │ ├── static-files.md │ ├── simple.md │ └── reading-parameters.md ├── getting-to-know │ ├── tooling.md │ ├── deno-object.md │ ├── install-deno.md │ ├── debugging.md │ ├── arguments-and-flags.md │ └── first-program.md ├── deploying │ ├── push.md │ ├── deploy.md │ └── containerize.md ├── oak │ ├── introducing-oak.md │ ├── simple-oak.md │ ├── oak-templates.md │ ├── oak-router.md │ └── static-files.md └── what-is │ ├── why-oh-why.md │ ├── dependencies.md │ ├── secure-by-default.md │ └── typescript-first.md ├── .editorconfig ├── .gitignore ├── src ├── pages │ ├── 404.js │ ├── index.js │ └── index.css ├── components │ ├── TOCCard.css │ └── TOCCard.js ├── util │ └── helpers.js ├── templates │ └── lessonTemplate.js └── layouts │ ├── index.css │ └── index.js ├── .github └── workflows │ └── gatsby.yml ├── .eslintrc.json ├── gatsby-node.js ├── gatsby-config.js ├── package.json ├── csv.js ├── README.md └── LICENSE /.prettierrc: -------------------------------------------------------------------------------- 1 | {} 2 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | } -------------------------------------------------------------------------------- /lessons/images/me.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/me.jpg -------------------------------------------------------------------------------- /lessons/images/zdnet.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/zdnet.jpg -------------------------------------------------------------------------------- /lessons/images/Expressjs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/Expressjs.png -------------------------------------------------------------------------------- /lessons/images/breakpoint.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/breakpoint.jpg -------------------------------------------------------------------------------- /lessons/images/contacts.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/contacts.jpeg -------------------------------------------------------------------------------- /lessons/images/dockerhub.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/dockerhub.jpg -------------------------------------------------------------------------------- /lessons/images/node-deno.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/node-deno.png -------------------------------------------------------------------------------- /lessons/images/node-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/node-logo.png -------------------------------------------------------------------------------- /lessons/images/chrome-debug.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/chrome-debug.jpg -------------------------------------------------------------------------------- /lessons/images/deno-deployed.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-deployed.jpg -------------------------------------------------------------------------------- /lessons/images/deno-object.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-object.jpg -------------------------------------------------------------------------------- /lessons/images/deno-styled.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-styled.jpg -------------------------------------------------------------------------------- /lessons/images/dockerhub-web.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/dockerhub-web.jpg -------------------------------------------------------------------------------- /lessons/images/edge-inspect.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/edge-inspect.jpg -------------------------------------------------------------------------------- /lessons/images/express-app.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/express-app.jpg -------------------------------------------------------------------------------- /lessons/images/image-latest.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/image-latest.jpg -------------------------------------------------------------------------------- /lessons/images/tagged-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/tagged-image.jpg -------------------------------------------------------------------------------- /lessons/images/what-i-know.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/what-i-know.png -------------------------------------------------------------------------------- /lessons/images/cosmos-options.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/cosmos-options.jpg -------------------------------------------------------------------------------- /lessons/images/default-oak-app.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/default-oak-app.jpg -------------------------------------------------------------------------------- /lessons/images/deno-extension.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-extension.jpg -------------------------------------------------------------------------------- /lessons/images/deno-info-path.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-info-path.jpg -------------------------------------------------------------------------------- /lessons/images/deno-templates.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-templates.jpg -------------------------------------------------------------------------------- /lessons/images/export-default.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/export-default.jpg -------------------------------------------------------------------------------- /lessons/images/oak-default-app.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/oak-default-app.jpg -------------------------------------------------------------------------------- /lessons/images/options-options.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/options-options.jpg -------------------------------------------------------------------------------- /lessons/images/simple-oak-app.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/simple-oak-app.jpg -------------------------------------------------------------------------------- /lessons/images/app-with-templates.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/app-with-templates.jpg -------------------------------------------------------------------------------- /lessons/images/chrome-hover-args.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/chrome-hover-args.jpg -------------------------------------------------------------------------------- /lessons/images/default-hostname.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/default-hostname.jpg -------------------------------------------------------------------------------- /lessons/images/deno-intellisense.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-intellisense.jpg -------------------------------------------------------------------------------- /lessons/images/handlebars-readme.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/handlebars-readme.jpg -------------------------------------------------------------------------------- /lessons/images/registry-provider.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/registry-provider.jpg -------------------------------------------------------------------------------- /lessons/images/simple-web-server.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/simple-web-server.jpg -------------------------------------------------------------------------------- /lessons/images/static-site-deps.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/static-site-deps.jpg -------------------------------------------------------------------------------- /lessons/images/stdlib-typescript.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/stdlib-typescript.jpg -------------------------------------------------------------------------------- /lessons/images/FrontendMastersLogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/FrontendMastersLogo.png -------------------------------------------------------------------------------- /lessons/images/always-in-workspace.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/always-in-workspace.jpg -------------------------------------------------------------------------------- /lessons/images/default-express-app.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/default-express-app.jpg -------------------------------------------------------------------------------- /lessons/images/denoexercises-image.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/denoexercises-image.jpg -------------------------------------------------------------------------------- /lessons/images/exercise-dockerfile.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/exercise-dockerfile.jpg -------------------------------------------------------------------------------- /lessons/images/integrated-terminal.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/integrated-terminal.jpg -------------------------------------------------------------------------------- /lessons/images/deno-vs-node-benchmarks.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/burkeholland/deno-first-look/HEAD/lessons/images/deno-vs-node-benchmarks.jpg -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | end_of_line = lf 5 | insert_final_newline = true 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Project dependencies 2 | # https://www.npmjs.org/doc/misc/npm-faq.html#should-i-check-my-node_modules-folder-into-git 3 | node_modules 4 | .cache/ 5 | # Build directory 6 | public/ 7 | .DS_Store 8 | yarn-error.log 9 | -------------------------------------------------------------------------------- /src/pages/404.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const NotFoundPage = () => ( 4 |
5 |

NOT FOUND

6 |

You just hit a route that doesn't exist... the sadness.

7 |
8 | ); 9 | 10 | export default NotFoundPage; 11 | -------------------------------------------------------------------------------- /src/components/TOCCard.css: -------------------------------------------------------------------------------- 1 | .main-card { 2 | border: 1px solid #ccc; 3 | border-radius: 8px; 4 | width: 100%; 5 | margin: 0; 6 | overflow: hidden; 7 | background-color: white; 8 | } 9 | 10 | .lesson-title { 11 | font-size: 20px; 12 | padding: 15px 30px; 13 | } 14 | 15 | .lesson-content { 16 | padding: 0 15px 15px 15px; 17 | line-height: 1.5; 18 | } 19 | 20 | .sections-name { 21 | list-style: none; 22 | } 23 | 24 | .lesson-section-title { 25 | margin-top: 25px; 26 | } 27 | -------------------------------------------------------------------------------- /.github/workflows/gatsby.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Gatsby Site to GitHub Pages 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | deploy: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@master 13 | - name: npm install, build, and csv 14 | run: | 15 | npm install 16 | npm run build 17 | npm run csv 18 | - name: Deploy site to gh-pages branch 19 | uses: alex-page/blazing-fast-gh-pages-deploy@v1.1.0 20 | with: 21 | repo-token: ${{ secrets.ACCESS_TOKEN }} 22 | site-directory: public 23 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "eslint:recommended", 4 | "plugin:import/errors", 5 | "plugin:react/recommended", 6 | "plugin:jsx-a11y/recommended", 7 | "prettier", 8 | "prettier/react" 9 | ], 10 | "rules": { 11 | "react/prop-types": 0, 12 | "jsx-a11y/label-has-for": 0, 13 | "no-console": 1 14 | }, 15 | "plugins": ["react", "import", "jsx-a11y"], 16 | "parser": "babel-eslint", 17 | "parserOptions": { 18 | "ecmaVersion": 2018, 19 | "sourceType": "module", 20 | "ecmaFeatures": { 21 | "jsx": true 22 | } 23 | }, 24 | "env": { 25 | "es6": true, 26 | "browser": true, 27 | "node": true 28 | }, 29 | "settings": { 30 | "react": { 31 | "version": "16.5.2" 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /gatsby-node.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | 3 | exports.createPages = ({ actions, graphql }) => { 4 | const { createPage } = actions; 5 | 6 | const lessonTemplate = path.resolve(`src/templates/lessonTemplate.js`); 7 | 8 | return graphql(` 9 | { 10 | allMarkdownRemark( 11 | sort: { order: DESC, fields: [frontmatter___order] } 12 | limit: 1000 13 | ) { 14 | edges { 15 | node { 16 | excerpt(pruneLength: 250) 17 | html 18 | id 19 | frontmatter { 20 | order 21 | path 22 | title 23 | } 24 | } 25 | } 26 | } 27 | } 28 | `).then(result => { 29 | if (result.errors) { 30 | return Promise.reject(result.errors); 31 | } 32 | 33 | result.data.allMarkdownRemark.edges.forEach(({ node }) => { 34 | createPage({ 35 | path: node.frontmatter.path, 36 | component: lessonTemplate 37 | }); 38 | }); 39 | }); 40 | }; 41 | -------------------------------------------------------------------------------- /src/util/helpers.js: -------------------------------------------------------------------------------- 1 | function splitSections(str) { 2 | const validSectionTest = /^\d+[A-Z]+$/; 3 | const numbersRegex = /^\d+/; 4 | const lettersRegex = /[A-Z]+$/; 5 | if (!validSectionTest.test(str)) { 6 | throw new Error( 7 | `${str} does not match the section format. It must be , like 16A or 5F (case sensitive)` 8 | ); 9 | } 10 | 11 | return [numbersRegex.exec(str)[0], lettersRegex.exec(str)[0]]; 12 | } 13 | 14 | const getCharScore = str => 15 | str 16 | .split("") 17 | .map((char, index) => char.charCodeAt(0) * 10 ** index) 18 | .reduce((acc, score) => acc + score); 19 | 20 | function sorter(a, b) { 21 | let aOrder, bOrder; 22 | 23 | if (a.attributes && a.attributes.order) { 24 | aOrder = a.attributes.order; 25 | bOrder = b.attributes.order; 26 | } else { 27 | aOrder = a.order; 28 | bOrder = b.order; 29 | } 30 | 31 | const [aSec, aSub] = splitSections(aOrder); 32 | const [bSec, bSub] = splitSections(bOrder); 33 | 34 | // sections first 35 | if (aSec !== bSec) { 36 | return aSec - bSec; 37 | } 38 | 39 | // subsections next 40 | return getCharScore(aSub) - getCharScore(bSub); 41 | } 42 | 43 | module.exports.splitSections = splitSections; 44 | module.exports.sorter = sorter; 45 | -------------------------------------------------------------------------------- /src/pages/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { StaticQuery, graphql } from "gatsby"; 3 | import Card from "../components/TOCCard"; 4 | 5 | import "./index.css"; 6 | 7 | const IndexPage = () => ( 8 | ( 36 |
37 |
38 |

{props.site.siteMetadata.title}

39 |

{props.site.siteMetadata.subtitle}

40 |
41 | 42 | 46 |
47 | )} 48 | /> 49 | ); 50 | 51 | export default IndexPage; 52 | -------------------------------------------------------------------------------- /lessons/permissions/permission-specificity.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/permissions/permission-specificity" 3 | title: "Permission Specificity" 4 | order: "5C" 5 | section: "5 - Permissions" 6 | description: "Burke explores the unique permissions model of Deno." 7 | --- 8 | 9 | > Make sure you are on the [5-permission-specificity](https://github.com/burkeholland/deno-exercises/tree/5-permission-specificity) branch to follow along with this section. 10 | 11 | ## Permission Specificity 12 | 13 | Permission in Deno come with a specificity qualifier that allows you to specify only the access your program needs. In the example above, we requested "read" access. That allows us to read any file or directory that the executing user can. It would be better if we restricted this access to use the directory that is going to be read. 14 | 15 | Modify the permission descriptor to specify the path that read access will be granted to. 16 | 17 | ```typescript 18 | const desc = { name: "read", path: "../" } as const; 19 | ``` 20 | 21 | Run the program again with `deno run --unstable app.ts`. Notice that this time, the prompt tells you what directory the program is requesting access to read. 22 | 23 | ```bash 24 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 25 | ️⚠️ Deno requests read access to "../". Grant? [g/d (g = grant, d = deny)] 26 | ``` 27 | 28 | It is better to ask for only the permissions your app needs. 29 | -------------------------------------------------------------------------------- /lessons/dependencies/compatiblity-with-node.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/dependencies/compatibility-with-node" 3 | title: "Compatibility With Node" 4 | order: "4E" 5 | section: "4 - Understanding Dependencies" 6 | description: "Burke dives into how Deno handles dependencies." 7 | --- 8 | 9 | One of the first questions that might pop into your head here is that there is a problem: Node is successful due to the massive library of packages. Are those packages compatible with Deno? 10 | 11 | Probably not. 12 | 13 | Deno **does** have a [Node compatibility module](https://deno.land/std@0.67.0/node/README.md) in its standard library. In theory, at some point, you would be able to import this module and all Node code would "just work". However, as of the time of this writing, of the 38 built-in Node modules, only 8 are supported in the Deno compatibility module. 14 | 15 | Furthermore, if the npm package you are using does any system calls, it will be built with `node-gyp`. Deno simply doesn't support this. It's built with [Rust](https://www.rust-lang.org/) and has an entirely different compiler called [Cargo](https://doc.rust-lang.org/cargo/) for bindings. This means that a lot of Node modules are simply going to "not work". However - there's a lot of smart people out there and I'm sure that this is a problem that will be solved at some point. 16 | 17 | Also, the third party list for Deno is growing rapidly already. As I typed this section I checked for my least favorite `node-gyp` requiring package - which is Sass. There is already a Sass library that you can use with Deno. 18 | -------------------------------------------------------------------------------- /src/components/TOCCard.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Link from "gatsby-link"; 3 | import * as helpers from "../util/helpers"; 4 | import "./TOCCard.css"; 5 | 6 | const sortFn = helpers.sorter; 7 | 8 | const LessonCard = ({ content, title }) => { 9 | console.log(sortFn); 10 | 11 | const sections = content 12 | .map(lesson => lesson.node.frontmatter) 13 | .sort(sortFn) 14 | .reduce((acc, lesson) => { 15 | if (!acc.length) { 16 | acc.push([lesson]); 17 | return acc; 18 | } 19 | 20 | const lastSection = acc[acc.length - 1][0].section.split(",")[0]; 21 | if (lastSection === lesson.section.split(",")[0]) { 22 | acc[acc.length - 1].push(lesson); 23 | } else { 24 | acc.push([lesson]); 25 | } 26 | 27 | return acc; 28 | }, []); 29 | 30 | return ( 31 |
32 |

{title}

33 |
34 |
    35 | {sections.map(section => ( 36 |
  1. 37 |

    {section[0].section}

    38 |
      39 | {section.map(lesson => ( 40 |
    1. 41 | {lesson.title} 42 |
    2. 43 | ))} 44 |
    45 |
  2. 46 | ))} 47 |
48 |
49 |
50 | ); 51 | }; 52 | 53 | export default LessonCard; 54 | -------------------------------------------------------------------------------- /src/pages/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #f9fafb; 3 | } 4 | 5 | .index { 6 | width: 97%; 7 | max-width: 750px; 8 | margin: 0 auto; 9 | margin-top: 20px; 10 | } 11 | 12 | .index .jumbotron { 13 | } 14 | 15 | .example-table { 16 | border-collapse: separate; 17 | } 18 | 19 | .example-table td { 20 | border: 1px solid black; 21 | width: 20px; 22 | height: 20px; 23 | } 24 | 25 | .example-table .current { 26 | background-color: #fcc; 27 | } 28 | 29 | .example-table .n { 30 | border-top-color: transparent; 31 | } 32 | 33 | .example-table .s { 34 | border-bottom-color: transparent; 35 | } 36 | 37 | .example-table .e { 38 | border-right-color: transparent; 39 | } 40 | 41 | .example-table .w { 42 | border-left-color: transparent; 43 | } 44 | 45 | .lesson-content table { 46 | } 47 | 48 | .lesson-content td { 49 | border: 1px solid black; 50 | padding: 8px; 51 | } 52 | 53 | .lesson-content td input { 54 | min-width: 300px; 55 | } 56 | 57 | .lesson-flex { 58 | display: flex; 59 | flex-direction: column; 60 | justify-content: center; 61 | align-items: center; 62 | } 63 | 64 | .random-tweet { 65 | width: 100%; 66 | margin-top: 100px; 67 | } 68 | 69 | .fem-link { 70 | text-align: center; 71 | } 72 | 73 | .main { 74 | margin: auto; 75 | max-width: 960px; 76 | } 77 | 78 | .navbar { 79 | border-bottom: none; 80 | } 81 | 82 | .navbar-content { 83 | max-width: 960px; 84 | margin: auto; 85 | } 86 | 87 | p { 88 | padding-top: 10px; 89 | } 90 | 91 | .gradient { 92 | background: #222222; 93 | /* background: linear-gradient( 94 | to bottom, 95 | rgb(15, 28, 51) 0%, 96 | rgb(73, 88, 114) 100% 97 | ); */ 98 | } 99 | -------------------------------------------------------------------------------- /gatsby-config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | siteMetadata: { 3 | title: "Deno First Look", 4 | subtitle: "An introduction to the Deno JavaScript runtime", 5 | description: "An introduction to the Deno JavaScript runtime", 6 | keywords: [ 7 | "this is", 8 | "a list of keywords and phrase", 9 | "that search engines", 10 | "will index your page for", 11 | ], 12 | }, 13 | pathPrefix: "/deno-first-look", 14 | plugins: [ 15 | `gatsby-plugin-layout`, 16 | { 17 | resolve: `gatsby-source-filesystem`, 18 | options: { 19 | path: `${__dirname}/lessons`, 20 | name: "markdown-pages", 21 | }, 22 | }, 23 | `gatsby-plugin-react-helmet`, 24 | { 25 | resolve: `gatsby-transformer-remark`, 26 | options: { 27 | plugins: [ 28 | `gatsby-remark-autolink-headers`, 29 | `gatsby-remark-copy-linked-files`, 30 | `gatsby-remark-prismjs`, 31 | { 32 | resolve: `gatsby-remark-images`, 33 | options: { 34 | maxWidth: 800, 35 | linkImagesToOriginal: true, 36 | sizeByPixelDensity: false, 37 | }, 38 | }, 39 | ], 40 | }, 41 | }, 42 | `gatsby-plugin-sharp`, 43 | { 44 | resolve: `gatsby-plugin-sharp`, 45 | options: { 46 | // Available options and their defaults: 47 | base64Width: 20, 48 | forceBase64Format: ``, // valid formats: png,jpg,webp 49 | useMozJpeg: process.env.GATSBY_JPEG_ENCODER === `MOZJPEG`, 50 | stripMetadata: true, 51 | defaultQuality: 100, 52 | failOnError: true, 53 | }, 54 | }, 55 | ], 56 | }; 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gatsby-course-starter", 3 | "description": "a gatsby seed project to get your education site started", 4 | "version": "1.0.0", 5 | "author": "Brian Holt ", 6 | "dependencies": { 7 | "bootstrap": "^4.5.2", 8 | "code-mirror-themes": "^1.0.0", 9 | "front-matter": "^4.0.2", 10 | "gatsby": "^2.24.53", 11 | "gatsby-cli": "^2.12.91", 12 | "gatsby-link": "^2.4.13", 13 | "gatsby-plugin-layout": "^1.3.10", 14 | "gatsby-plugin-react-helmet": "^3.3.10", 15 | "gatsby-plugin-sharp": "^2.6.31", 16 | "gatsby-remark-autolink-headers": "^2.3.11", 17 | "gatsby-remark-copy-linked-files": "^2.3.13", 18 | "gatsby-remark-images": "^3.3.28", 19 | "gatsby-remark-prismjs": "^3.5.11", 20 | "gatsby-source-filesystem": "^2.3.27", 21 | "gatsby-transformer-remark": "^2.8.32", 22 | "is-url-superb": "^4.0.0", 23 | "parse-markdown-links": "^1.0.4", 24 | "prismjs": "^1.21.0", 25 | "react": "^16.13.1", 26 | "react-dom": "^16.13.1", 27 | "react-helmet": "^6.1.0" 28 | }, 29 | "keywords": [ 30 | "gatsby", 31 | "gatsby-starter", 32 | "course", 33 | "education" 34 | ], 35 | "license": "(CC-BY-NC-4.0 OR Apache-2.0)", 36 | "main": "n/a", 37 | "scripts": { 38 | "build": "gatsby build --prefix-paths", 39 | "csv": "node csv.js", 40 | "dev": "gatsby develop", 41 | "format": "prettier --write \"src/**/*.{js,jsx,md,css}\"", 42 | "lint": "eslint \"src/**/*.{js,jsx}\"" 43 | }, 44 | "devDependencies": { 45 | "@babel/polyfill": "^7.11.5", 46 | "babel-eslint": "^10.1.0", 47 | "core-js": "^3.6.5", 48 | "eslint": "^7.8.1", 49 | "eslint-config-prettier": "^6.11.0", 50 | "eslint-plugin-import": "^2.22.0", 51 | "eslint-plugin-jsx-a11y": "^6.3.1", 52 | "eslint-plugin-react": "^7.20.6", 53 | "prettier": "^2.1.1" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /lessons/welcome/exercises.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/exercises" 3 | title: "How to use the exercises" 4 | order: "1B" 5 | section: "1 - Welcome" 6 | description: "Burke covers the agenda for the Deno First Look workshop, talks about himself a little bit more than you would probably like, explains how to submit issues with this course and then pontificates on whether or not Deno is something that has a future and if we should be investing valuable time into learning it." 7 | --- 8 | 9 | The steps that I'll go through in this workshop are also available as a repo with exercises where you can follow along.sThe repo is called [Deno Exercises](https://github.com/burkeholland/deno-exercises). All you need to do to use it is to clone it. 10 | 11 | ## Using the exercise project 12 | 13 | The Deno Exercise project has branches for all of the different sections in this workshop. For instance, if the section we're on is "Oak Templates" in chapter 7, the branch you need to be on to follow along is "7-oak-templates". This convention is used for every section, although not every section has an exercise. 14 | 15 | Some sections build on each other. This becomes especially true when we get to the Oak section. If you get lost at any point, these sections contain a "solutions" folder that should have the working code. 16 | 17 | ## The Deno dev container 18 | 19 | Deno Exercises also contain a ".devcontainer" definition. What this does it preconfigures an environment where Deno is already installed and fully functional. You won't need to install anything, it will "just work". 20 | 21 | To use this Dev Container, you need to have the [Remote-Containers extension for VS Code](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers?WT.mc_id=devcloud_0000_buhollan), as well as Docker Desktop installed. Note that if you are on Windows, it's highly recommended that you also have WSL2 enabled as the backing subsystem for Docker. 22 | -------------------------------------------------------------------------------- /lessons/permissions/determining-permissions.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/permissions/determining-permissions" 3 | title: "Determining Permissions" 4 | order: "5D" 5 | section: "5 - Permissions" 6 | description: "Burke explores the unique permissions model of Deno." 7 | --- 8 | 9 | > Make sure you are on the [5-determining-permissions](https://github.com/burkeholland/deno-exercises/tree/5-determining-permissions) branch to follow along with this section. 10 | 11 | The "permissions" API in Deno allows you to "query" for a specific permission to see if you have it or not. This gives you a chance to ask for it if it doesn't already exist. Although, if the permissions is already granted, the code requesting the permission again will not run, and the "state" will be "granted". 12 | 13 | The default "state" of any permissions is always "prompt". 14 | 15 | Modify the `app.ts` file to query for the state of the "read" permission and log it out 16 | 17 | ```typescript 18 | const desc = { name: "read", path: "." } as const; 19 | 20 | console.log(await Deno.permissions.query(desc)); 21 | 22 | const status = await Deno.permissions.request(desc); 23 | 24 | console.log(await Deno.permissions.query(desc)); 25 | 26 | if (status.state === "granted") { 27 | const results = await Deno.readDir("."); 28 | for await (const result of results) { 29 | console.log(result); 30 | } 31 | } else { 32 | console.log("This program requires 'read' permissions to execute"); 33 | } 34 | ``` 35 | 36 | Execute the program with `deno run --unstable app.ts`. 37 | 38 | You should see the status object in the terminal with an initial value of "prompt" and then "granted" or "denied" based on whether or not you chose to give the program access. 39 | 40 | ```bash 41 | PermissionStatus { state: "prompt" } 42 | ️⚠️ Deno requests read access to ".". Grant? [g/d (g = grant, d = deny)] d 43 | PermissionStatus { state: "denied" } 44 | This program requires 'read' permissions to execute 45 | ``` 46 | -------------------------------------------------------------------------------- /src/templates/lessonTemplate.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Link from "gatsby-link"; 3 | import { graphql } from "gatsby"; 4 | import * as helpers from "../util/helpers"; 5 | 6 | const sortFn = helpers.sorter; 7 | 8 | export default function Template(props) { 9 | let { markdownRemark, allMarkdownRemark } = props.data; // data.markdownRemark holds our post data 10 | 11 | const sections = allMarkdownRemark.edges 12 | .map(lesson => lesson.node.frontmatter) 13 | .sort(sortFn); 14 | 15 | const { frontmatter, html } = markdownRemark; 16 | 17 | const index = sections.findIndex(el => el.path === frontmatter.path); 18 | 19 | const prevLink = 20 | index > 0 ? ( 21 | 22 | {"← " + sections[index - 1].title} 23 | 24 | ) : null; 25 | const nextLink = 26 | index < sections.length - 1 ? ( 27 | 28 | {sections[index + 1].title + " →"} 29 | 30 | ) : null; 31 | return ( 32 |
33 |
34 |

{frontmatter.title}

35 |

{frontmatter.date}

36 |
40 |
41 | {prevLink} 42 | {nextLink} 43 |
44 |
45 |
46 | ); 47 | } 48 | 49 | export const pageQuery = graphql` 50 | query LessonByPath($path: String!) { 51 | markdownRemark(frontmatter: { path: { eq: $path } }) { 52 | html 53 | frontmatter { 54 | path 55 | title 56 | order 57 | section 58 | description 59 | } 60 | } 61 | allMarkdownRemark(limit: 1000) { 62 | edges { 63 | node { 64 | frontmatter { 65 | order 66 | path 67 | title 68 | } 69 | } 70 | } 71 | } 72 | } 73 | `; 74 | -------------------------------------------------------------------------------- /lessons/images/logo.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /lessons/webserver/static-files.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/webserver/static-files" 3 | title: "Serving up static files" 4 | order: "6C" 5 | section: "6 - Building a Webserver" 6 | description: "Burke looks at how to build a simple web server with Deno" 7 | --- 8 | 9 | > Make sure you are on the [6-serving-up-static-files](https://github.com/burkeholland/deno-exercises/tree/6-serving-up-static-files) branch to follow along with this exercise. 10 | 11 | Normally, we serve up HTML files with a web server. These are also called "static files", because the server doesn't change them, it just serves them. They are static. 12 | 13 | One way to serve a static file would be to read the file with the Deno object. There is an "index.html" file already in the project. Let's use the `Deno` object to read that file off of disk and serve it up. 14 | 15 | Modify the `for` loop to use the `Deno.readFile` method to read the "index.html" file. 16 | 17 | ```typescript 18 | for await (const req of server) { 19 | const html = await Deno.readFile("index.html"); 20 | 21 | req.respond({ 22 | body: html, 23 | }); 24 | } 25 | ``` 26 | 27 | Run the app. Since we're reading the disk now, we'll have to pass in the `--allow-read` flag as well. 28 | 29 | ```bash 30 | deno run --allow-net=0.0.0.0:3000 --allow-read=. app.ts 31 | ``` 32 | 33 | This is one way to serve a static file. But Deno provides a "file server" module as part of its Standard Library 34 | 35 | ## Serving static content with Deno Standard Library 36 | 37 | Import the "file-server" module from the Deno standard library. 38 | 39 | ```typescript 40 | import { serveFile } from "https://deno.land/std/http/file_server.ts"; 41 | ``` 42 | 43 | Modify the `for` loop to use the `serveFile` method to serve up the "index.html" file. 44 | 45 | ```typescript 46 | for await (const req of server) { 47 | const html = await serveFile(req, "index.html"); 48 | 49 | req.respond(html); 50 | } 51 | ``` 52 | 53 | Run the program with the "--allow-net" and "--allow-read" flags 54 | 55 | ```bash 56 | deno run --allow-net=0.0.0.0:3000 --allow-read=. app.ts 57 | ``` 58 | 59 | > Note that you can pass `-A` which stands for "allow all" so you don't have to pass multiple permissions flags. Handy for development." 60 | 61 | Now we're serving up static files. But a proper web server needs to handle routes. 62 | -------------------------------------------------------------------------------- /lessons/permissions/requesting-permission.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/permissions/requesting-permissions" 3 | title: "Requesting Permissions" 4 | order: "5B" 5 | section: "5 - Permissions" 6 | description: "Burke explores the unique permissions model of Deno." 7 | --- 8 | 9 | > Make sure you are on the [5-requesting-permissions](https://github.com/burkeholland/deno-exercises/tree/5-requesting-permissions) branch to follow along with this exercise. 10 | 11 | Deno has a permissions API that will allow you to request certain access from your code as a library author. 12 | 13 | In the "app.ts" file, define a `const` object which specifies the name of the "read" permission. 14 | 15 | ```typescript 16 | const desc = { name: "read" } as const; 17 | ``` 18 | 19 | Pass the descriptor object to the `request` method on `Deno.permissions`. Because the permissions API is still unstable, it does not show up in intellisense under the "Deno" object. 20 | 21 | ```typescript 22 | const desc = { name: "read" } as const; 23 | const status = await Deno.permissions.request(desc); 24 | ``` 25 | 26 | The "status" variable will contain a "state" object after the user has either granted or denied permissions. If the permission is granted, the state will be "granted". If it is denied, then "denied". 27 | 28 | Check the `state` object on the `status` constant to make sure permission has been granted. If so, list all the files in the current directory. 29 | 30 | ```typescript 31 | const desc = { name: "read", path: "." } as const; 32 | const status = await Deno.permissions.request(desc); 33 | 34 | console.log(status); 35 | 36 | if (status.state === "granted") { 37 | const results = await Deno.readDir("."); 38 | for await (const result of results) { 39 | console.log(result); 40 | } 41 | } else { 42 | console.log("This program requires 'read' permissions to execute"); 43 | } 44 | ``` 45 | 46 | Run the program from the terminal with `deno run --unstable app.ts`. 47 | 48 | You should see a prompt in the terminal asking you if you want to grant or deny permission to "read". 49 | 50 | ```bash 51 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 52 | ️⚠️ Deno requests read access. Grant? [g/d (g = grant, d = deny)] 53 | ``` 54 | 55 | Enter "g" to grant or "d" to deny and view the output. 56 | 57 | > Note that if you run this program with the `--allow-read` flag, the permissions request will be ignored and the "status.state" value will be "granted". 58 | -------------------------------------------------------------------------------- /lessons/getting-to-know/tooling.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/getting-to-know/tooling" 3 | title: "Tooling" 4 | order: "3B" 5 | section: "3 - Getting to know Deno" 6 | description: "Burke covers how to install Deno, and takes a look at the Deno CLI, REPL and what options you need to be aware of." 7 | --- 8 | 9 | > Switch to the [3-tooling](https://github.com/burkeholland/deno-exercises/tree/3-tooling) branch to follow along with this section 10 | 11 | Tooling is available for Deno in the form of the Deno VS Code extension. The primary value of the extension is that it provides intellisense for Deno and a debugger. 12 | 13 | ![The Deno extension](../images/deno-extension.jpg) 14 | 15 | The extension is installed from the VS Code Extension gallery either through VS Code, or via the [extension gallery web site](https://marketplace.visualstudio.com/items?itemName=denoland.vscode-deno). 16 | 17 | By default, the extension won't appear to do anything. This is because it is disabled by default. You'll need to enable the Deno extension for your Deno code by adding the following line to your **Workspace** settings. Workspace is bolded there because that is what Deno recommends that you do, and at the time of this writing, enabling it in your user settings appears to have no affect. 18 | In VS Code, open the Command Palette and select "Preferences: Open Workspace Settings (JSON)". When you do that, a new folder will be added to your project called ".vscode". Inside there is a "settings.json" file. These settings ONLY apply to the current project and are not global. The file should be empty. Add the following line to enable the Deno extension. 19 | 20 | ```json 21 | "deno.enable": true 22 | ``` 23 | 24 | Once you change this setting, reload the editor by selecting "Reload Window" from the Command Palette in VS Code. I have been unable to get the extension to work without doing this after first install. There may also be occasions where the extension stops working. In this case, a "Reload Window" usually solves the problem. 25 | 26 | To test that the extension is working, open the "app.ts" file in the "exercise" folder. Type the "Deno" global variable and press the ".". This should trigger VS Code's intellisense, which will show you all of the methods available off of the global "Deno" object. 27 | 28 | ![Deno intellisense](../images/deno-intellisense.jpg) 29 | 30 | Great! You've got Deno installed and you've got the tooling that you need. It's time to write our first program using Deno. 31 | -------------------------------------------------------------------------------- /lessons/deploying/push.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/deploying/push-to-image-registry" 3 | title: "Pushing the Deno image to a registry" 4 | order: "8B" 5 | section: "8 - Deploying" 6 | description: "Burke looks at how to deploy an application built with Deno" 7 | --- 8 | 9 | ## Prerequisites 10 | 11 | To complete this section, you'll need the following things... 12 | 13 | - Azure CLI 14 | - Docker Extension for VS Code 15 | - An Azure Account 16 | 17 | Containers can run pretty much anywhere these days. You can run them on your own hardware, or you can send one up into the cloud and run it there. Since we don't have a data center, we'll be sending our Deno container up to the cloud. 18 | 19 | We could push to Docker hub, Azure, GitLab - anywhere that provides a container registry. Docker hub is probably the most commonly used registry, so we'll push our image there, and then pull it into a hosting provider 20 | 21 | ## Pushing the image to a registry 22 | 23 | First we need to push our image to a registry. In the "Registries" section of the Docker Explorer, click the "Connect Registry" link to connect to a registry. 24 | 25 | ![](../images/dockerhub.jpg) 26 | 27 | Select "Docker Hub" from the list. You'll need to sign in with your Docker username and password. Once you do that, you'll see your username under the Docker Hub item in the explorer view. 28 | 29 | To push the Deno image to Docker hub, we need to tag it with the registry name. In my case, the registry name is "burkeholland". 30 | 31 | In the "Image" explorer, find the "denoexercises" node with the "latest" image. 32 | 33 | ![](../images/image-latest.jpg) 34 | 35 | Right-click this image and select "Tag". Tag is by putting your registry name in front of the image name. 36 | 37 | You should now see a second image in the explorer that contains the newly created tag. 38 | 39 | ![](../images/tagged-image.jpg) 40 | 41 | Right-click the "latest" image under /denoexercises and select "Push". 42 | 43 | Take the default tag (we've already tagged it) and press enter. 44 | 45 | The terminal should open and you'll see your image being pushed up to Docker hub. 46 | 47 | Go back to the "registries" view and expand your username node. You should see the newly created image in the list. Right-click it and select "Open in Browser". This will take you to your image on Docker hub. 48 | 49 | ![](../images/dockerhub-web.jpg) 50 | 51 | The image has now been published to Docker hub. This means that we can pull it with a hosting provider and see our app running in production. 52 | -------------------------------------------------------------------------------- /lessons/dependencies/think-like-a-browser.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/dependencies/think-like-a-browser" 3 | title: "Thinking like a browser" 4 | order: "4A" 5 | section: "4 - Understanding Dependencies" 6 | description: "Burke dives into how Deno handles dependencies." 7 | --- 8 | 9 | You'll remember from the earlier introduction section that Deno thinks differently about dependencies. It's a core design premise. But we didn't talk about _how_ it's different. 10 | 11 | Deno tries to stay as close to browser conventions as possible everywhere that it can. And how do you include a JavaScript file in a browser? You reference it with a script tag. If it's on a CDN, you might do it like this... 12 | 13 | ```html 14 | 15 | ``` 16 | 17 | Deno works the same way. You require in dependencies by URL. If you are requiring a local dependency, it's just the relative path. If you are using a third-party library, you do it by the URL. 18 | 19 | Deno follows the [ECMAScript standard](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export) for `import/export` syntax. 20 | 21 | ## Caching 22 | 23 | Caching is an important part of how Deno handles dependencies. Since it uses the URL reference as the method to include them, you wouldn't want it to try and download those every time you ran the program. 24 | 25 | Instead, Deno downloads a dependency the first time that you run the program and until the dependency changes or you force an update, that cache is where the dependency is served from. 26 | 27 | How Deno handles dependencies is different based on whether or not you are using a local dependency (importing a file in the current project) or a remote dependency (referencing a third-party module by URL). In the next few sections, we'll look at how Deno handles these two scenarios, and some best practices for organizing dependencies in Deno. 28 | 29 | ## Getting Dependency Info 30 | 31 | As we move through the next sections, the `deno info` command may come in handy. By itself, the command returns the location of your Deno cache. Try it out and see what you get... 32 | 33 | ```bash 34 | deno info 35 | ``` 36 | 37 | Here's what I get... 38 | 39 | ```bash 40 | DENO_DIR location: "/home/burkeholland/.cache/deno" 41 | Remote modules cache: "/home/burkeholland/.cache/deno/deps" 42 | TypeScript compiler cache: "/home/burkeholland/.cache/deno/gen" 43 | ``` 44 | 45 | We'll be looking at these directories going forward. If you get stuck or can't find the cache, a simple `deno info` should get you there. 46 | -------------------------------------------------------------------------------- /lessons/dependencies/best-practices.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/dependencies/best-practices" 3 | title: "Best Practices" 4 | order: "4D" 5 | section: "4 - Understanding Dependencies" 6 | description: "Burke dives into how Deno handles dependencies." 7 | --- 8 | 9 | We've already established that Deno would like to stay as close to browser conventions as possible, and in that case, importing from a URL feels less icky. But it's sure not very pleasant to look at. You wouldn't really want a bunch of imported URL's just hanging out all over your code. That's no way to live your life. 10 | 11 | Deno recommends that you do all of your importing in a root file called `deps.ts` and export from that single file. That way all of your deps are in the same place, and all of the URL's are centralized to that one file. Later on in this workshop, we'll be building a full website with Deno and the `deps.ts` file for that project looks like this. 12 | 13 | ```typescript 14 | import { 15 | Application, 16 | Context, 17 | Router, 18 | send, 19 | } from "https://deno.land/x/oak/mod.ts"; 20 | import { Handlebars } from "https://deno.land/x/handlebars/mod.ts"; 21 | 22 | export { Application, Context, Router, send, Handlebars }; 23 | ``` 24 | 25 | Then our application code stays clean, and only references the `deps.ts` file. 26 | 27 | The common pushback I hear on this idea is "I can't install the module if I'm on an airplane". That is true. But you also can't install npm modules if you are on an airplane. Nothing changes here. npm packages have to be downloaded. Deno modules have to be downloaded. Period. The only difference is that Deno is using the URL as the top level construct on which to identify the module, and npm downloads it and uses a specific location - node_modules. 28 | 29 | For those who still aren't convinced, let me leave you with this thought: Someone once suggested that we put HTML in JavaScript. I laughed at that person when I first heard that suggestion. Today, React is quite possibly the most popular JavaScript framework in the world, and we don't think twice about putting HTML in our JavaScript. In fact, it works quite well. In my humble opinion, having your markup and code in the same component file is BETTER than not. It's a better developer experience. 30 | 31 | I'm not saying that Deno is the React of JavaScript runtimes. I'm not saying that importing from URL's is going to ultimately be the better developer experience. But I am saying that sometimes we have to allow ourselves to examine possibilities that don't look so good on the surface. 32 | 33 | Give it a chance. I think you'll find that it's a relatively simple solution to the dependency problem. 34 | -------------------------------------------------------------------------------- /lessons/dependencies/local-dependencies.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/dependencies/local-dependencies" 3 | title: "Local dependencies" 4 | order: "4B" 5 | section: "4 - Understanding Dependencies" 6 | description: "Burke dives into how Deno handles dependencies." 7 | --- 8 | 9 | > Make sure you are on the [4-local-depedencies](https://github.com/burkeholland/deno-exercises/tree/4-local-dependencies) branch to follow along with this section. 10 | 11 | First let's look at how Deno handles local dependencies. We'll do that by creating a local dependency and importing it into our main "app.ts" file. 12 | 13 | - Add a file to the project called "utils.ts". 14 | - Add a const called "utils". 15 | - Add a function to that const that reverses a string. 16 | - Export the `utils` constant as the default export. 17 | 18 | ```typescript 19 | const utils = { 20 | reverse(text: string) { 21 | return text.split("").reverse().join(); 22 | }, 23 | }; 24 | 25 | export default utils; 26 | ``` 27 | 28 | In the "app.ts" file, require the `utils` module. Note that you will have to specify the file extension. Unlike Node, Deno does not allow you to import a module without an extension. This is the one way in which it differs from the ECMAScript spec. 29 | 30 | ```typescript 31 | import utils from "./utils.ts"; 32 | ``` 33 | 34 | From the "app.ts" file, call the `reverse` method and log out the value. 35 | 36 | ```typescript 37 | import utils from "./utils.ts"; 38 | 39 | console.log(utils.reverse("Hello World")); 40 | ``` 41 | 42 | Execute the program and review the output... 43 | 44 | ```bash 45 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 46 | dlroW olleH 47 | ``` 48 | 49 | Let's examine how Deno handled this dependency locally. 50 | 51 | - Open the generated output by navigating to the Deno cache folder... 52 | 53 | Linux 54 | 55 | ``` 56 | ~/.cache/deno/gen/file/ 57 | 58 | // on my machine, it looks like this... 59 | ~/.cache/deno/gen/file/home/burkeholland/dev/deno-first-look-excercises 60 | ``` 61 | 62 | Windows 63 | 64 | ```powershell 65 | C:\Users\burkeholland\AppData\Local\deno\gen\file\ 66 | 67 | // on my machine, it looks like this... 68 | C:\Users\burkeholland\AppData\Local\deno\gen\file\C\dev\burkeholland\deno-first-look-exercises 69 | ``` 70 | 71 | You should see the following files present... 72 | 73 | - app.ts.buildinfo 74 | - app.ts.js 75 | - app.ts.js.map (This file may or may not be present. If it's not, it's because sourcemaps are included in the app.ts.js file.) 76 | - app.ts.meta 77 | - utils.ts.js 78 | - utils.ts.meta 79 | 80 | If you open the `app.ts.js` file, you'll see that the utils file is being included and it's output has been transpiled here. 81 | 82 | This should look familiar based on what we reviewed during the TypeScript section. Next we'll look at how this changes (or doesn't) when you install dependencies from other sources. Remote Dependencies. 83 | -------------------------------------------------------------------------------- /lessons/deploying/deploy.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/deploying/deploy-deno-image" 3 | title: "Deploying the Deno image" 4 | order: "8C" 5 | section: "8 - Deploying" 6 | description: "Burke looks at how to deploy an application built with Deno" 7 | --- 8 | 9 | ## Prerequisites 10 | 11 | To complete this section, you'll need the following things... 12 | 13 | - [Azure CLI](https://docs.microsoft.com/cli/azure/install-azure-cli?WT.mc_id=devcloud-0000-buhollan) 14 | - [Free Azure Account](https://azure.microsoft.com/en-us/free/) 15 | 16 | Now that we've pushed the image to Docker hub, we can pull it in from a cloud hosting provider. Nearly all providers support containers. For the purposes of this section, we'll be using Azure. 17 | 18 | ## Creating the site 19 | 20 | The Azure Service that we need to host a website in a container is called "App Service". App Service allows you to host a container in Azure with your website inside. 21 | 22 | Using the Azure CLI, make sure you are logged in... 23 | 24 | ```bash 25 | az login 26 | ``` 27 | 28 | Next, create a Resource Group. Resource Groups are just how Azure resources are organized. You can think of them like projects. A project might have a database, a website, some analytics - all of those are different Azure services, but we would want them all in the same resource group to help us stay organized. 29 | 30 | ```bash 31 | az group create -l westus -n "deno-exercise-group" 32 | ``` 33 | 34 | Now we need to specify what sort of computing power we want for the site we're going to create. That's done with something called "service plans". A service plan says what kind of operating system you want - Windows or Linux - and how much compute you need. This is where you are spending money in so much as you get what you pay for. For this demonstration, we'll use the F1 - which is the free tier. Finally, we're specifying that we want Linux hosting as Windows is the default. 35 | 36 | ```bash 37 | az appservice plan create -g deno-exercise-group -n deno-service-plan --sku F1 --is-linux 38 | ``` 39 | 40 | Last, we create the site and tell it to pull our image from Docker hub. 41 | 42 | ```bash 43 | az webapp create -n deno-exercise -g deno-exercise-group -p deno-service-plan -i burkeholland/denoexercises 44 | ``` 45 | 46 | > Web app names in Azure have to be unique, so if the command fails, try a different name than "deno-exercise". 47 | 48 | Let's just review what all those flags were, cause there are a few of them... 49 | 50 | - -n = name of the web app 51 | - -g = name of the Resource Group 52 | - -p = name of the Service Plan 53 | - -i = name of the image to pull and run 54 | 55 | It takes just a minute for the site to start the container for the first time. You can find the URL for your new site by looking at the output from the last command (there is a lot of it - I know) and finding the "defaultHostName" property... 56 | 57 | ![](../images/default-hostname.jpg) 58 | 59 | Copy that URL and paste it into a browser tab and... 60 | 61 | ![](../images/deno-deployed.jpg) 62 | 63 | Rock and roll! We successfully built a full-on web app with Deno and deployed it to a proper cloud. 64 | -------------------------------------------------------------------------------- /lessons/permissions/granting-permissions.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/permissions/granting-permissions" 3 | title: "Granting Permissions" 4 | order: "5A" 5 | section: "5 - Permissions" 6 | description: "Burke explores the unique permissions model of Deno." 7 | --- 8 | 9 | > Make sure you are on the [5-granting-permissions](https://github.com/burkeholland/deno-exercises/tree/5-granting-permissions) branch to follow along with this section. 10 | 11 | One of the core principles of Deno is "secure by default". As we discussed in the section of the same name, this means that by default, Deno can't do very much without your permission. It can't read your file system, it can't make HTTP calls - it's completely sandboxed. 12 | 13 | In the "app.ts" file, attempt to read all of the files in the current directory. This can be done with the "Deno" object "read" method. 14 | 15 | ```typescript 16 | const results = await Deno.readDir("../"); 17 | 18 | for await (const result of results) { 19 | console.log(result); 20 | } 21 | ``` 22 | 23 | Execute "app.ts" from the terminal 24 | 25 | ```bash 26 | deno run app.ts 27 | ``` 28 | 29 | This should throw an error saying that you don't have read access. 30 | 31 | ```bash 32 | error: Uncaught (in promise) PermissionDenied: read access to ".", run again with the --allow-read flag 33 | at processResponse (core.js:226:13) 34 | at Object.jsonOpAsync (core.js:244:12) 35 | at async Object.[Symbol.asyncIterator] (deno:cli/rt/30_fs.js:125:16) 36 | at async file:///home/burkeholland/dev/deno-first-look-exercises/app.ts:3:18 37 | ``` 38 | 39 | It says to run again with the `--allow-read` flag. Let's do that. 40 | 41 | ```bash 42 | deno run --allow-read app.ts 43 | ``` 44 | 45 | This time Deno reads the contents of the current directory and writes them out to the terminal. 46 | 47 | ```bash 48 | { name: "README.md", isFile: true, isDirectory: false, isSymlink: false } 49 | { name: ".git", isFile: false, isDirectory: true, isSymlink: false } 50 | { name: "app.ts", isFile: true, isDirectory: false, isSymlink: false } 51 | { name: ".vscode", isFile: false, isDirectory: true, isSymlink: false } 52 | { name: "utils.ts", isFile: true, isDirectory: false, isSymlink: false } 53 | ``` 54 | 55 | Note that by default, the `--allow-read` flag lets the program read anything that the executing account can read. It's possible to pass a path to the `--allow-read` flag that restricts the access to a certain directory. 56 | 57 | Run the program again with the following command 58 | 59 | ```bash 60 | deno run --allow-read=. app.ts 61 | ``` 62 | 63 | The program now fails. This is because we didn't give it enough access. We said it could read the current directory "exercise", but the program is trying to read the parent directory. 64 | 65 | Try it again passing in the parent path... 66 | 67 | ```bash 68 | deno run --allow-read=../ app.ts 69 | ``` 70 | 71 | The program should run successfully. 72 | 73 | Passing flags like this is how you explicitly give code elevated access. But it is not the only way. The other way to get elevated access in Deno is to request it from the code itself. This is more akin to the way that apps on your phone will ask for access to your location, photos, notifications, etc. 74 | -------------------------------------------------------------------------------- /src/layouts/index.css: -------------------------------------------------------------------------------- 1 | .gradient { 2 | background: rgb(96, 108, 136); 3 | background: linear-gradient( 4 | to bottom, 5 | rgb(96, 108, 136) 0%, 6 | rgb(63, 76, 107) 100% 7 | ); 8 | } 9 | 10 | .navbar { 11 | border-bottom: 1px solid #ccc; 12 | position: sticky; 13 | width: 100%; 14 | top: 0; 15 | z-index: 10; 16 | display: flex; 17 | justify-content: space-between; 18 | align-items: center; 19 | } 20 | 21 | .navbar h1 { 22 | font-size: 20px; 23 | margin: inherit; 24 | padding: inherit; 25 | font-weight: bold; 26 | } 27 | 28 | .navbar h2 { 29 | font-size: 14px; 30 | margin: inherit; 31 | padding: inherit; 32 | text-transform: uppercase; 33 | color: white; 34 | } 35 | 36 | .jumbotron.gradient { 37 | color: white; 38 | text-transform: uppercase; 39 | font-weight: bold; 40 | } 41 | 42 | .navbar-brand.navbar-brand { 43 | text-transform: uppercase; 44 | color: white; 45 | font-weight: bold; 46 | } 47 | 48 | .navbar-brand.navbar-brand:hover { 49 | color: #777; 50 | } 51 | 52 | .navbar-brand.navbar-brand:focus { 53 | color: white; 54 | } 55 | 56 | .lesson { 57 | margin: 15px; 58 | padding: 15px; 59 | background-color: #fff; 60 | border-radius: 8px; 61 | } 62 | 63 | .lesson p { 64 | clear: both; 65 | } 66 | 67 | .lesson-links { 68 | font-size: 18px; 69 | padding: 15px 0; 70 | } 71 | 72 | .next { 73 | float: right; 74 | } 75 | 76 | .prev { 77 | float: left; 78 | } 79 | 80 | .lesson-title { 81 | color: white; 82 | text-transform: uppercase; 83 | font-weight: bold; 84 | } 85 | 86 | .klipse-result { 87 | border: 1px solid #90b4fe; 88 | padding-top: 8px; 89 | position: relative; 90 | width: 100%; 91 | } 92 | 93 | .klipse-result .CodeMirror-wrap { 94 | width: 100%; 95 | border-color: transparent; 96 | } 97 | 98 | .klipse-result::before { 99 | content: "result"; 100 | background-color: white; 101 | position: absolute; 102 | top: -13px; 103 | height: 13px; 104 | } 105 | 106 | .language-htm, 107 | .language-css, 108 | .language-js, 109 | .language-json { 110 | width: 100%; 111 | } 112 | 113 | .gatsby-highlight { 114 | /* border: 1px solid black; */ 115 | padding: 4px; 116 | border-radius: 4px; 117 | display: flex; 118 | justify-content: space-between; 119 | flex-direction: column; 120 | align-items: stretch; 121 | } 122 | 123 | .CodeMirror-wrap { 124 | width: 100%; 125 | font-size: 12px; 126 | height: inherit; 127 | margin-bottom: 12px; 128 | } 129 | 130 | .CodeMirror-gutters { 131 | height: inherit !important; 132 | } 133 | 134 | .klipse-snippet > .CodeMirror { 135 | border: none; 136 | width: 100%; 137 | } 138 | 139 | .gatsby-highlight > .klipse-snippet { 140 | border: 1px solid #90b4fe; 141 | width: 100%; 142 | border-right: none; 143 | position: relative; 144 | margin-bottom: 15px; 145 | } 146 | 147 | .doggos { 148 | width: 100%; 149 | border: 1px solid #666; 150 | border-radius: 5px; 151 | } 152 | 153 | blockquote { 154 | margin-top: 20px; 155 | background-color: #FDF6E3; 156 | padding: 0px 10px; 157 | 158 | border: 1px solid #FDF6E3; 159 | } 160 | -------------------------------------------------------------------------------- /csv.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs").promises; 2 | const path = require("path"); 3 | const fm = require("front-matter"); 4 | const isUrl = require("is-url-superb"); 5 | const parseLinks = require("parse-markdown-links"); 6 | const { sorter } = require("./src/util/helpers"); 7 | const mdDir = process.env.MARKDOWN_DIR || path.join(__dirname, "lessons/"); 8 | const outputPath = 9 | process.env.OUTPUT_CSV_PATH || path.join(__dirname, "public/lessons.csv"); 10 | const linksOutputPath = 11 | process.env.LINKS_CSV_PATH || path.join(__dirname, "public/links.csv"); 12 | 13 | async function createCsv() { 14 | console.log(`making the markdown files into a CSV from ${mdDir}`); 15 | 16 | // get paths 17 | const allFiles = await fs.readdir(mdDir); 18 | const files = allFiles.filter(filePath => filePath.endsWith(".md")); 19 | 20 | // read paths, get buffers 21 | const buffers = await Promise.all( 22 | files.map(filePath => fs.readFile(path.join(mdDir, filePath))) 23 | ); 24 | 25 | // make buffers strings 26 | const contents = buffers.map(content => content.toString()); 27 | 28 | // make strings objects 29 | let frontmatters = contents.map(fm); 30 | 31 | // find all attribute keys 32 | const seenAttributes = new Set(); 33 | frontmatters.forEach(item => { 34 | Object.keys(item.attributes).forEach(attr => seenAttributes.add(attr)); 35 | }); 36 | const attributes = Array.from(seenAttributes.values()); 37 | 38 | if (attributes.includes("order")) { 39 | frontmatters = frontmatters.sort(sorter); 40 | } 41 | 42 | // get all data into an array 43 | let rows = frontmatters.map(item => { 44 | const row = attributes.map(attr => 45 | item.attributes[attr] ? JSON.stringify(item.attributes[attr]) : "" 46 | ); 47 | return row; 48 | }); 49 | 50 | // header row must be first row 51 | rows.unshift(attributes); 52 | 53 | // join into CSV string 54 | const csv = rows.map(row => row.join(",")).join("\n"); 55 | 56 | // write file out 57 | await fs.writeFile(outputPath, csv); 58 | 59 | console.log(`Wrote ${rows.length} rows to ${outputPath}`); 60 | 61 | // make links csv 62 | let longestLength = 0; 63 | let linksArray = frontmatters.map(row => { 64 | const links = parseLinks(row.body).filter(isUrl); 65 | longestLength = longestLength > links.length ? longestLength : links.length; 66 | const newRow = [row.attributes.order, row.attributes.title, ...links]; 67 | return newRow; 68 | }); 69 | 70 | if (longestLength) { 71 | // add title row 72 | linksArray = linksArray.map(array => { 73 | const lengthToFill = longestLength + 2 - array.length; 74 | return array.concat(Array.from({ length: lengthToFill }).fill("")); 75 | }); 76 | 77 | linksArray.unshift( 78 | ["order", "title"].concat( 79 | Array.from({ length: longestLength }).map((_, index) => `link${index}`) 80 | ) 81 | ); 82 | 83 | // join into CSV string 84 | const linksCsv = linksArray.map(row => row.join(",")).join("\n"); 85 | 86 | // write file out 87 | await fs.writeFile(linksOutputPath, linksCsv); 88 | 89 | console.log(`Wrote ${linksArray.length} rows to ${linksOutputPath}`); 90 | } 91 | } 92 | 93 | createCsv(); 94 | -------------------------------------------------------------------------------- /lessons/oak/introducing-oak.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/oak/introducing-oak" 3 | title: "Introducing Oak" 4 | order: "7A" 5 | section: "7 - Oak web framework" 6 | description: "Burke introduces the Oak web framework for Deno" 7 | --- 8 | 9 | Just like Node.js has the Express web framework, Deno has a web framework as well. It's called Oak. And since Deno loves anagrams, Oak is an anagram for Koa. Koa is a web framework for Node built on the concept of generators. It's not as popular as Express given that generators haven't taken off syntactically. You might not agree with that statement, but I think it's objectively obvious that we don't see generators in much of the JavaScript code out in the wild. Or maybe you see them. But I don't. 10 | 11 | While Oak is modeled after Koa, it's more useful to compare it to Express because that will be the paradigm that more developers are familiar with, and that's definitely true for _this_ developer. 12 | 13 | ![Express JS Logo](../images/Expressjs.png) 14 | 15 | Oak is modeled after Koa and Koa is the successor to Express. Given all of that, the syntax for Oak looks a lot like the syntax for Express. The big difference is that Oak does not come with all of the baked-in middleware that Express does. Middleware is code that executes on the request to the server. Middleware can do all sorts of things, from providing templating to handling cookies and so on and so forth. 16 | 17 | Express also provides a nice scaffolding tool that has made it's adoption rather quick. This generator scaffolds out an opinionated folder structure that helps get you moving in the right direction. 18 | 19 | In this next section, we're going to build an opinionated project structure for Oak that mimics what you get today with Express. Before we do that, let's look at what Express does today. 20 | 21 | ## Generating an Express app 22 | 23 | Generate a new Express App with Handlebars template support 24 | 25 | ```bash 26 | npx express-generator --hbs my-express-app && cd my-express-app && npm i 27 | ``` 28 | 29 | Open the application in your editor 30 | 31 | Run it from your terminal with `npm start`. 32 | 33 | ![Default Express app in browser](../images/default-express-app.jpg) 34 | 35 | Examine the project in your editor 36 | 37 | ![Express app open in VS Code](../images/express-app.jpg) 38 | 39 | - Examine the `app.js` file. Note that Express puts all of it's application setup logic in the `app.js` file. 40 | - Examine the "views" folder. Note that there is a layout, index and error template. 41 | - Examine the "routes" folder. Note that the specific route logic is handled in these files 42 | - Examine the "public" folder. Note that any files that are placed in this folder can be referenced in the template files via the "public" relative URL. 43 | - Examine the "bin" folder. Note that the `www` file contained inside is the entry point of the application. 44 | 45 | We're going to replicate this exact same application setup and build this same default Express app with the Oak framework. This will give us a chance to see how Oak handles routing, templates, static files and other concepts we'll need for a proper web framework. The end result will look almost identical to the default Express App. 46 | 47 | ![Default Oak app in browser](../images/oak-default-app.jpg) 48 | -------------------------------------------------------------------------------- /lessons/webserver/simple.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/webserver/simple" 3 | title: "Building a simple webserver" 4 | order: "6A" 5 | section: "6 - Building a Webserver" 6 | description: "Burke looks at how to build a simple web server with Deno" 7 | --- 8 | 9 | > Make sure you are on the [6-building-a-simple-webserver](https://github.com/burkeholland/deno-exercises/tree/6-building-a-simple-webserver) branch to follow along with this section. 10 | 11 | One of the most common use-cases for a JavaScript runtime is a web server. Web servers are a common way of exposing APIs and building full stack data-driven applications. 12 | 13 | The Deno standard library contains a `server` module that lets you implement in a web server in just a few lines of code. 14 | 15 | First, import the `server` module from the Deno standard library into the "app.ts" file. 16 | 17 | ```typescript 18 | import { serve } from "https://deno.land/std/http/server.ts"; 19 | ``` 20 | 21 | Next, we'll, define `HOSTNAME` and `PORT` constants. For the `HOSTNAME`, we'll use 0.0.0.0, which is the same as saying "localhost" or "127.0.0.1", but is more compatible with things like Docker. 22 | 23 | ```typescript 24 | import { serve } from "https://deno.land/std/http/server.ts"; 25 | const PORT = 3000; 26 | const HOSTNAME = "0.0.0.0"; 27 | ``` 28 | 29 | The only thing you need from the `server` library is the `serve` function. All you need to do is call that function and pass in the hostname and port to get a new server instance. 30 | 31 | ```typescript 32 | import { serve } from "https://deno.land/std/http/server.ts"; 33 | 34 | const PORT = 3000; 35 | const HOSTNAME = "0.0.0.0"; 36 | 37 | const server = serve({ hostname: HOSTNAME, port: PORT }); 38 | ``` 39 | 40 | The server has been created, but it doesn't do anything because we aren't handling the requests. As awkward as this may seem, we're going to run an infinite `for` loop and handle any request that comes in by setting the `respond` property on the request. 41 | 42 | Use a `for` loop to start the server and listen for any incoming request. The body contains a simple response of "Hello World". 43 | 44 | ```typescript 45 | import { serve } from "https://deno.land/std/http/server.ts"; 46 | 47 | const PORT = 3000; 48 | const HOSTNAME = "0.0.0.0"; 49 | 50 | const server = serve({ hostname: HOSTNAME, port: PORT }); 51 | 52 | console.log(`Server is now running on: http://${HOSTNAME}:${PORT}`); 53 | 54 | for await (const req of server) { 55 | req.respond({ 56 | body: "Hello World", 57 | }); 58 | } 59 | ``` 60 | 61 | Run the program with `deno run app.ts`. It should tell you that permission is denied and that the `allow-net` flag is required. 62 | 63 | ```bash 64 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 65 | error: Uncaught PermissionDenied: network access to "0.0.0.0:3000", run again with the --allow-net flag 66 | ``` 67 | 68 | Run the program again with the `--allow-net` flag. Be sure to restrict the access to only port 3000. 69 | 70 | ```bash 71 | deno run --allow-net=0.0.0.0:3000 app.ts 72 | ``` 73 | 74 | The server should now be running on port 3000. When you visit it in the browser, you should see "Hello World". 75 | 76 | ![Simple web server returning hello world](../images/simple-web-server.jpg) 77 | 78 | ## Returning HTML 79 | 80 | Returning text isn't terribly useful, so instead, return some HTML. 81 | 82 | ```app.ts 83 | for await (const req of server) { 84 | req.respond({ 85 | body: "

Hello World

", 86 | }); 87 | } 88 | ``` 89 | 90 | > Make sure you restart the server. You can also run with the --watch flag so that the server is restarted every time you make changes. 91 | 92 | OK - that's about as simple a web server as we can get. Let's take a look at some common web server type scenarios. 93 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

gatsby-course-starter


2 | 3 |

4 | A Gatsby starter to get you started creating educational materials using Markdown 5 |

6 | 7 | ## Get Started 8 | 9 | 1. `npm install --global gatsby-cli` - make sure you're on Gatsby v2+ 10 | - See [docs here](https://next.gatsbyjs.org/docs/) if you need help 11 | 1. `gatsby new course-website https://github.com/btholt/gatsby-course-starter` 12 | 1. `cd course-website` 13 | 1. `npm run dev` 14 | 1. Open http://localhost:8000 in your browser 15 | 16 | ## Lessons 17 | 18 | The crux of this site is are the lessons. Provided are two examples. Each lesson needs a [frontmattter](https://github.com/gatsbyjs/gatsby/blob/master/docs/docs/adding-markdown-pages.md#note-on-creating-markdown-files) `path`, `order`, and `title`. Generally you should make the `path` and the file name match for ease of finding it. 19 | 20 | - `path` - needs a leading slash. This will be slug of the lesson 21 | - `title` - will be the title displayed on the Table of Contents and on the page itself 22 | - `order` - the order of which the item should appear in the table of contents. should in `` format where the number corresponds to the section it's and the letter corresponds to the order of the lesson inside the section, e.g. `3B` 23 | - `section` - the title of the section that the article is in. Only the first lesson for each section will be used. 24 | - `description` – a one-to-three sentence summary of the lesson. used for the meta tag for social shares and SEO. if no description is given, the `siteMetadata.description` for the site is used 25 | 26 | ## Config 27 | 28 | Inside of `gatsby-config.js` be sure to fill out the `siteMetadata` fields, including `title`, `subtitle`, `description`, and `keywords`. 29 | 30 | ## GitHub Pages 31 | 32 | If you do want to deploy to GitHub pages, make sure you add the name of the repo to the `pathPrefix` property in `gatsby-config.js` so that it will correctly make all the links. 33 | 34 | ## GitHub Actions 35 | 36 | This site is ready to deployed to GitHub Pages out of the box with GitHub Actions. If you do not want to deploy this to GitHub Pages, delete the `.github` directory. 37 | 38 | If you do want to deploy this to GitHub Pages with GitHub Actions, you need to do a few things. 39 | 40 | 1. Create a [personal access token](https://help.github.com/en/articles/creating-a-personal-access-token-for-the-command-line) with rights to read and write to repos. 41 | 1. Put that token in your repos secrets. Click the Settings tab and paste your access token in the Secrets tab with the key `ACCESS_TOKEN`. 42 | 1. Now once you commit your code, it should automatically deploy your GitHub Pages site should deploy automatically! 43 | 44 | ## Example Sites 45 | 46 | - [This repo itself](https://btholt.github.io/gatsby-course-starter/) 47 | - [Complete Intro to Containers](https://btholt.github.io/complete-intro-to-containers/) 48 | - [Complete Intro to React v5](https://btholt.github.io/complete-intro-to-react-v5/) 49 | - [Complete Intro to Web Dev v2](https://btholt.github.io/intro-to-web-dev-v2/) 50 | - [Four Semesters of Computer Science in Five Hours Part II](https://btholt.github.io/four-semesters-of-cs-part-two/) 51 | 52 | ## CSV 53 | 54 | If you run `npm run csv`, a CSV will be generated with all the various lessons' frontmatter outputted to `public/lessons.csv`. You can change the path by changing the `OUTPUT_CSV_PATH` environment variable. 55 | 56 | Another CSV will be output to `public/links.csv` where it pull all the links out of each lesson and put them into a CSV. This path can be modified by setting the `LINKS_CSV_PATH` environment variable. 57 | 58 | ## License 59 | 60 | The **code** is this repo is licensed under the Apache 2.0 license. 61 | 62 | I include the CC-BY-NC-4.0 license for the content; this is what I recommend you license your **content** under: anyone can use and share the content but they cannot sell it; only you can. 63 | -------------------------------------------------------------------------------- /src/layouts/index.js: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import Link from "gatsby-link"; 3 | import Helmet from "react-helmet"; 4 | import { graphql, StaticQuery } from "gatsby"; 5 | 6 | import "bootstrap/dist/css/bootstrap.css"; 7 | import "prismjs/themes/prism-solarizedlight.css"; 8 | import "code-mirror-themes/themes/monokai.css"; 9 | import "./index.css"; 10 | 11 | // import jpg from "../../static/posterframe.jpg"; 12 | 13 | const TemplateWrapper = props => { 14 | return ( 15 | { 17 | const frontmatter = 18 | props.data && props.data.markdownRemark 19 | ? props.data.markdownRemark.frontmatter 20 | : null; 21 | 22 | return ( 23 |
24 | 70 |
71 | 79 |
80 |
{props.children}
81 |
82 | ); 83 | }} 84 | query={graphql` 85 | query HomePage($path: String!) { 86 | markdownRemark(frontmatter: { path: { eq: $path } }) { 87 | html 88 | frontmatter { 89 | path 90 | title 91 | order 92 | section 93 | description 94 | } 95 | } 96 | site { 97 | pathPrefix 98 | siteMetadata { 99 | title 100 | subtitle 101 | description 102 | keywords 103 | } 104 | } 105 | } 106 | `} 107 | /> 108 | ); 109 | }; 110 | 111 | export default TemplateWrapper; 112 | -------------------------------------------------------------------------------- /lessons/getting-to-know/deno-object.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/getting-to-know/deno-object" 3 | title: "The Deno object" 4 | order: "3D" 5 | section: "3 - Getting to know Deno" 6 | description: "Burke looks at how to pass arguments and flags to the Deno CLI" 7 | --- 8 | 9 | > Make sure you are on the [3-the-deno-object](https://github.com/burkeholland/deno-exercises/tree/3-the-deno-object) branch to follow along with this section. 10 | 11 | Just like a browser has a top-level "window" object, Deno has a top level "Deno" object. Much of the functionality that you would expect to find in certain Node modules is built in to this global object. 12 | 13 | ## Inspect the Deno object 14 | 15 | In VS Code, type `Deno` and then hit the `.`. The intellisense should come up. Use the arrow keys to cycle through the list of items that are on the Deno object. 16 | 17 | ![The deno object](../images/deno-object.jpg) 18 | 19 | Notice that most of these methods are for interacting with the system. This includes things like `chown` for changing file permissions, and the APIs for creating file, reading files and writing to files. 20 | 21 | Deno also has a standard library that you can import as a dependency. This can be confusing. It can be hard to know what functionality is on the Deno object, and what you might need the Standard Library for. 22 | 23 | As a good rule of thumb, look on the Deno object before you look in the Standard Library. Most of what you need can be found without a dependency. 24 | 25 | ## Deno object replacement for Node concepts 26 | 27 | The Deno object replaces many of the concepts that you'll find in Node in various places. 28 | 29 | ### args 30 | 31 | Node.js has the `process.argv` object. This returns every argument on the terminal - including "node", the path to the file being executed and every argument after that. 32 | 33 | Deno has an "args" object which contains an array of _just_ the arguments. 34 | 35 | Add the following code to "app.ts" 36 | 37 | ```typescript 38 | console.log(Deno.args); 39 | ``` 40 | 41 | Execute the program and pass in some arguments 42 | 43 | ```bash 44 | deno run app.ts Hello World 1 2 45 | [ "Hello", "World", "1", "2" ] 46 | ``` 47 | 48 | ### env 49 | 50 | In Node.js, you access environment variables by looking at the `process.env` object. 51 | 52 | In Deno, the `process` object does not exist. Instead, look on the `Deno.env` object. 53 | 54 | Add the following to the `app.ts` file 55 | 56 | ```typescript 57 | console.log(Deno.env.get("DEVELOPMENT")); 58 | ``` 59 | 60 | Execute the program from the terminal, passing in the environment variable the same way you normally would in Node. 61 | 62 | ```bash 63 | DEVELOPMENT=true deno run app.ts 64 | ``` 65 | 66 | The command fails! And this is your first look at "Secure By Default". You cannot read env variables without explicitly giving the program permission to do so. 67 | 68 | ```bash 69 | DEVELOPMENT=true deno run --allow-env app.ts 70 | ``` 71 | 72 | The program runs and returns "true". 73 | 74 | ### \_\_dirname 75 | 76 | In Node.js, there is a `__dirname` constant that tells you what the full path is to the current directory. 77 | 78 | In Deno, this constant doesn't exist. Instead, you'll use the `Deno.cwd()` method, which returns the same value as the `__dirname` const. 79 | 80 | Replace the code in `app.ts` with the following... 81 | 82 | ```typescript 83 | console.log(Deno.cwd()); 84 | ``` 85 | 86 | Execute the file from the terminal 87 | 88 | ```bash 89 | deno run app.ts 90 | ``` 91 | 92 | Failed again! You cannot read the file system without specific access. Pass in the "--allow-read" flag. 93 | 94 | ```bash 95 | deno run --allow-read app.ts 96 | ``` 97 | 98 | The program runs and should return the path to the current directory. 99 | 100 | You've seen what you can do in Deno with just the `Deno` object. It's important to know that much of what you need to do with the file system is built in to the Deno object. You don't need any additional dependencies. 101 | -------------------------------------------------------------------------------- /lessons/oak/simple-oak.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/oak/simple-oak" 3 | title: "A Simple Oak Server" 4 | order: "7B" 5 | section: "7 - Oak web framework" 6 | description: "Burke introduces the Oak web framework for Deno" 7 | --- 8 | 9 | > Make sure you switch to the [7-simple-oak-server](https://github.com/burkeholland/deno-exercises/tree/7-oak-simple-server) branch to follow along with this section. 10 | 11 | Oak is a [third-party library for Deno](https://oakserver.github.io/oak/). It's just like using an npm package with Node. 12 | 13 | In the `app.ts` file, import the `Application` object from the Oak library... 14 | 15 | ```typescript 16 | import { Application } from "https://deno.land/x/oak/mod.ts"; 17 | ``` 18 | 19 | Create a new instance of both the `Application` class... 20 | 21 | ```typescript 22 | import { Application } from "https://deno.land/x/oak/mod.ts"; 23 | 24 | const app = new Application(); 25 | ``` 26 | 27 | Define a handler for the request. This is middleware. 28 | 29 | ```typescript 30 | app.use((ctx, next) => { 31 | ctx.response.body = "Hello World"; 32 | }); 33 | ``` 34 | 35 | Tell the app to listen on port 3000. 36 | 37 | ```typescript 38 | import { Application } from "https://deno.land/x/oak/mod.ts"; 39 | 40 | const app = new Application(); 41 | 42 | app.use((ctx, next) => { 43 | ctx.response.body = "Hello World"; 44 | }); 45 | 46 | console.log(`Now listening on http://0.0.0.0:3000`); 47 | app.listen("0.0.0.0:3000"); 48 | ``` 49 | 50 | - Run the app with the `--allow-net`, `--unstable` and `--watch` flags. 51 | 52 | ```bash 53 | deno run --allow-net --unstable app.ts 54 | ``` 55 | 56 | Visit the application in a browser window on port 3000. 57 | 58 | > Note that if you didn't stop the previous application we built in the Web Server exercise, you may still have something running on port 3000. If that's the case, make sure you quit that process. 59 | 60 | ![](../images/simple-oak-app.jpg) 61 | 62 | ## Middleware 63 | 64 | The `app.use` function is middleware. It is a function that lets you do things with the request. You can have as many of these as you want. they will execute in order. The `ctx` object contains the current server context. The `next` function must be called to notify Oak that this piece of middleware is done executing and it can move on to the next. 65 | 66 | This is kind of abstract, so let's look at it in action. 67 | 68 | Add another handler above the one which returns the body. 69 | 70 | ```typescript 71 | import { Application } from "https://deno.land/x/oak/mod.ts"; 72 | 73 | const app = new Application(); 74 | 75 | app.use((ctx, next) => { 76 | console.log("This is middleware"); 77 | }); 78 | 79 | app.use((ctx, next) => { 80 | ctx.response.body = "Hello World"; 81 | }); 82 | 83 | console.log(`Now listening on http://0.0.0.0:3000`); 84 | app.listen("0.0.0.0:3000"); 85 | ``` 86 | 87 | Save the file and reload the browser window. 88 | 89 | This time the terminal will log out "This is middleware". But the request never resolves. This is because Deno is waiting for you to call `next` so that it can run the _next_ piece of middleware, which sets the body of the response. 90 | 91 | Modify the middleware with the log statement to call `next`. 92 | 93 | ```typescript 94 | import { Application } from "https://deno.land/x/oak/mod.ts"; 95 | 96 | const app = new Application(); 97 | 98 | app.use((ctx, next) => { 99 | console.log("This is middleware"); 100 | next(); 101 | }); 102 | 103 | app.use((ctx, next) => { 104 | ctx.response.body = "Hello World"; 105 | }); 106 | 107 | console.log(`Now listening on http://0.0.0.0:3000`); 108 | app.listen("0.0.0.0:3000"); 109 | ``` 110 | 111 | Save the file and refresh the browser. 112 | 113 | This time, the terminal logs out the message and then the page is returned. 114 | 115 | You can write pieces of middleware that can be passed to the `app.use` function. One of these pieces of middleware that we'll be using is the Deno router. In the next section we'll look at how to implement the router middleware for Deno. 116 | -------------------------------------------------------------------------------- /lessons/getting-to-know/install-deno.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/getting-to-know/install" 3 | title: "Installing Deno" 4 | order: "3A" 5 | section: "3 - Getting to know Deno" 6 | description: "Burke covers how to install Deno, and takes a look at the Deno CLI, REPL and what options you need to be aware of." 7 | --- 8 | 9 | Deno can be installed via cURL, Homebrew, PowerShell, Chocolatey - you name it. [Check the Deno docs](https://deno.land/#installation) for official instructions. For the sake of brevity, we'll use the cURL/PowerShell commands for this class. 10 | 11 | #### cURL 12 | 13 | ```bash 14 | curl -fsSL https://deno.land/x/install/install.sh | sh 15 | ``` 16 | 17 | #### PowerShell 18 | 19 | ```powershell 20 | iwr https://deno.land/x/install/install.ps1 -useb | iex 21 | ``` 22 | 23 | That's it. You can verify that deno is installed by opening a terminal and just running Deno. This opens the Deno REPL. 24 | 25 | ```bash 26 | $> deno 27 | ``` 28 | 29 | > REPL stands for "Run Eval Print Loop" 30 | 31 | Go ahead and write some JavaScript there - maybe a nice `console.log`. That seems like the write thing to do... 32 | 33 | ```bash 34 | Deno 1.4.6 35 | exit using ctrl+d or close() 36 | > console.log("Hello World"); 37 | Hello World 38 | undefined 39 | > 40 | ``` 41 | 42 | That outputs "Hello World" because we did the console.log, and then it prints "undefined" because that's the return value of the console.log method. Every method in JavaScript returns a result - even if you don't explicitly do it. 43 | 44 | Like the Node.js REPL, the Deno REPL will automatically add new lines when it sees that you are trying to write a multiline program. Try creating a new function which takes in a parameter and then outputs that with the world "Hello" in front. Then return the input parameter as the output. 45 | 46 | ```bash 47 | >function hello(who) { 48 | console.log(`Hello ${who}`); 49 | return who; 50 | } 51 | ``` 52 | 53 | When you add the closing brace, Deno REPL automatically exits out of edit mode. Note that Node.js does this same thing. 54 | 55 | Unlike Node.js, the Deno does not support editor mode. In Node.js, you can have the REPL go into editor mode by specifying the ".editor" option in the REPL. 56 | 57 | ```bash 58 | $> node 59 | Welcome to Node.js v12.19.0. 60 | Type ".help" for more information. 61 | > .editor 62 | // Entering editor mode (^D to finish, ^C to cancel) 63 | ``` 64 | 65 | Deno will just ignore that ".editor" command. However, we don't spend a lot of time coding in REPL's so - probably not a feature you're going to miss. 66 | 67 | ## What is Deno written in? 68 | 69 | By the way, any guesses on what language the native bindings for Deno are written in? Both Deno and Node use V8 as the JavaScript runtime, but the bindings that allow you to reach out of V8 and onto the native operating system are different. 70 | 71 | For Deno, it says right at the top, but it's more fun to look at source code, so let's do that instead. 72 | 73 | If you look at the ["core" folder](https://github.com/denoland/deno/tree/master/core) in the Deno repo, you'll see that all the files have a `.rs` extension. That file extension is for the language [Rust](https://www.rust-lang.org/). Rust is a language that was designed for highly safe concurrent systems. What they mean by that is that it is memory safe. It's kind of like C++, but it doesn't allow things like null pointers. And it was written by the folks at Mozilla, with some contributions from Brendan Eich - whose name might ring a bell because he's the guy who created JavaScript. So we haven't fallen too far from the apple tree here. Node.js native bindings are written in a combination of C and C++. 74 | 75 | You might remember I mentioned earlier that when Ryan created Node.js, he was mostly interested in I/O. That's important to note because as of right now, Node.js is faster in terms of HTTP server performance than Deno is, although according to [Deno's benchmarks](https://deno.land/benchmarks), the difference isn't stark. 76 | 77 | ![Benchmark for Deno vs Node HTTP Performance](../images/deno-vs-node-benchmarks.jpg) 78 | 79 | So, not a huge gap to close for Deno. I've often heard this complaint about Deno when comparing it to Node.js, and I'm just not sure the difference is great enough to care and certainly not a gap too big for Deno to close. And besides, most of us are not working with systems that are going to experience the kind of load that is going to necessitate agonizing over a chart like the one above. 80 | -------------------------------------------------------------------------------- /lessons/dependencies/remote-dependencies.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/dependencies/remote-dependencies" 3 | title: "Remote dependencies" 4 | order: "4C" 5 | section: "4 - Understanding Dependencies" 6 | description: "Burke dives into how Deno handles dependencies." 7 | --- 8 | 9 | > Make sure you are on the [4-remote-dependencies](https://github.com/burkeholland/deno-exercises/tree/4-remote-dependencies) branch to follow along with this section. 10 | 11 | "Remote" dependencies are how Deno handles what you would know today as "npm" packages. These are libraries that you might consume and use that someone else has written. 12 | 13 | Deno maintains a list of [approved third-party modules](https://deno.land/x) on their site. In fact, we'll use some of them later in this course. 14 | 15 | Deno also has a "Standard Library" that you will probably use quite a bit. These would be modules that are considered "built-in" by Node. 16 | 17 | For instance, Node has a "path" module that is frequently used. If you wanted to get the file name from a path, you could use the `path` module and `basename` method. 18 | 19 | ```javascript 20 | const path = require("path"); 21 | 22 | console.log(path.basename("/files/folders/folder/file.txt")); 23 | ``` 24 | 25 | The Deno standard library also has a "path" module. In Deno, the exact same functionality looks like this... 26 | 27 | ```typescript 28 | import * as path from "https://deno.land/std@0.73.0/path/mod.ts"; 29 | 30 | console.log(path.basename("/files/folders/folder/file.txt")); 31 | ``` 32 | 33 | > You'll see this "mod" file name a lot in Deno. It's the standard way of naming modules. It's short for "module". It's not required by Deno, it's just the standard naming they use. 34 | 35 | Both of these do the exact same thing and return the exact same result. The big difference is that you had to include the module by URL. 36 | 37 | - Run the second one in the `app.ts` file 38 | - Notice the output... 39 | 40 | ```bash 41 | Check file:///home/burkeholland/dev/burkeholland/deno-exercises/exercise/app.ts 42 | file.txt 43 | ``` 44 | 45 | Deno downloads all of the dependences specified in the `mod.ts` file which we imported to get the whole path module. 46 | 47 | Let's examine again what happened here by navigating to the generated output for the project... 48 | 49 | Linux 50 | 51 | ```bash 52 | ~/.cache/deno/gen/file/ 53 | 54 | // on my machine, it looks like this... 55 | ~/.cache/deno/gen/file/home/burkeholland/dev/deno-first-look-excercises 56 | ``` 57 | 58 | Windows 59 | 60 | ```powershell 61 | C:\Users\burkeholland\AppData\Local\deno\gen\file\ 62 | 63 | // on my machine, it looks like this... 64 | C:\Users\burkeholland\AppData\Local\deno\gen\file\C\dev\burkeholland\deno-first-look-exercises 65 | ``` 66 | 67 | The `app.ts` file now looks like this... 68 | 69 | ```javascript 70 | import * as path from "https://deno.land/std@0.73.0/path/mod.ts"; 71 | console.log(path.basename("/files/folders/folder/file.txt")); 72 | //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjo... 73 | ``` 74 | 75 | But we know that Deno doesn't download that file every time we run the program. We know that the first time we try and use it, Deno downloads it to the "deps" cache. 76 | 77 | Linux 78 | 79 | ```bash 80 | ~/.cache/deno/gen/file/ 81 | 82 | // on my machine, it looks like this... 83 | ~/.cache/deno/deps/https/deno.land 84 | ``` 85 | 86 | Windows 87 | 88 | ```powershell 89 | C:\Users\burkeholland\AppData\Local\deno\deps\https\deno.land 90 | 91 | // on my machine, it looks like this... 92 | C:\Users\burkeholland\AppData\Local\deno\deps\https\deno.land 93 | ``` 94 | 95 | The "deps" cache now contains a bunch more files. These are the dependencies that were downloaded to your machine. This is the equivalent of an "npm install". Deno uses the metadata files to find the dependencies you need right on your own machine. It won't try and download these again unless you change the version or force an update. 96 | 97 | But how do we know what dependencies were installed? This is where the info command comes in again. 98 | 99 | We can run `deno info app.ts` and it will show us a tree of the dependencies that the "path" mod from the Standard Library pulled in. 100 | 101 | ![](../images/deno-info-path.jpg) 102 | 103 | Now let's take a moment and address the elephant in the room - which is that importing modules from URL's feels... completely nuts. 104 | -------------------------------------------------------------------------------- /lessons/what-is/why-oh-why.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/what-is/why-oh-why" 3 | title: "What & Why" 4 | order: "2A" 5 | description: "Why oh why do we need another JavaScript runtime?" 6 | section: "2 - What is Deno" 7 | --- 8 | 9 | Deno is a command-line runtime for JavaScript. This means that it allows JavaScript to run outside of the browser. This is often referred to as "JavaScript on the server". This allows JavaScript to do I/O type of things like reading and writing to files on disk, or handling incoming requests and working with streams of data. Basically, the runtime frees JavaScript from the browser and promotes it to a first-class language like C# or Java. 10 | 11 | If you've been writing JavaScript for a while, you are probably familiar with an existing runtime that already does this, called, "Node". 12 | 13 | ![](../images/node-logo.png) 14 | 15 | "Deno" is an anagram for Node. It is literally the letters in "Node" rearranged to make a different word. This is not an inconsequential detail. If you were going to build a completely new runtime for JavaScript, why would you use the name Node, and just mix up the letters? If it's not Node, then why not call it something entirely different? 16 | 17 | ![deno anagram of node logo](../images/node-deno.png) 18 | 19 | In order to understand this, we need to first address a different question, which is why, oh why, do we need yet another runtime environment? 20 | 21 | ## Why Oh Why Do We Need Deno? 22 | 23 | If you've been in technology for any amount of time, you know that things move quickly. Nowhere do they move more quickly than in the world of JavaScript. It seems like we have a new library or framework every month. Yesterday's best practices are today's anti-patterns. It can be incredibly frustrating to try and build a profession in such churn. 24 | 25 | My gut reaction to hearing about Deno was "please no". We already have Node. I know Node. Node powers not just my apps, but also my development environment. It powers the tools that I use to build applications. npm is a critical part of virtually any JavaScript project and if you don't believe that, just look at it's [recent acquisition by GitHub](https://github.blog/2020-03-16-npm-is-joining-github/). I'm open to new ideas, but if we're going to do it, they need to solve major problems and provide some enormous benefits over what I'm doing right now. Because constant switching to the latest and "best" technology is a great way to accrue massive amounts of technical debt. 26 | 27 | Deno was created by Ryan Dahl. Ryan is the same person who created Node. Ryan points out that when he initially created Node, he was primarily concerned with I/O operations. To be even more specific, he bemoaned Apache HTTP Server, which was the most popular web server at the time. Specifically, the fact that Apache struggled with large numbers of concurrent connections. Also the fact that the prominent paradigm for web server code at the time was code that was executed from top to bottom in order. If any operation along the way took a long time, the rest of the code would be blocked from executing and this affected performance. All to say that when Ryan created Node, he did it to create a highly performant way of handling http requests. 28 | 29 | And he accomplished that goal. In 2012, Ryan left the project because he considered it mostly "done". Fast forward to today, and we know that Node has changed significantly since 2012. It's also given Ryan a lot of time to reflect and there are many things that he regrets now about Node. 30 | 31 | In his talk "10 things I regret about Node", Ryan looks back with 20/20 hindsight on some of the things in Node that he wishes were don't differently. 32 | 33 | 34 | 35 | Now, no software is perfect. JavaScript is not perfect. PHP is not perfect. Java is not perfect. There are always things that we do, decisions that we make where we are prognosticating about the future. We don't really know how things will play out when we write code, and we try and make the best decisions with the information we have. Living with regret is not typically a healthy thing, and hindsight is always 20/20. But Ryan's Node regrets are important in this context, because they lay the foundation for why Deno exists. 36 | 37 | Deno is Ryan's second attempt at creating a command-line runtime for JavaScript based on the mistakes that he feels like he made when he built Node. That's why it's an anagram. It is intentionally meant by Ryan to be a perfection of the ideas of Node, while fixing what he considers major flaws that are baked into the foundation of Node. It's important to understand what those regrets are, because the oddities of Deno will make much more sense. 38 | -------------------------------------------------------------------------------- /lessons/getting-to-know/debugging.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/getting-to-know/debugging" 3 | title: "Debugging" 4 | order: "3F" 5 | section: "3 - Getting to know Deno" 6 | description: "Burke looks at how to debug Deno apps" 7 | --- 8 | 9 | > Make sure you are on the [3-debugging](https://github.com/burkeholland/deno-exercises/tree/3-debugging) branch in the "exercise" folder to follow along with this section. 10 | 11 | Deno apps can be debugged either from the browser, or with VS Code. Much like Node, Deno has `--inspect` and `--inspect-brk` flags. The `--inspect` flag starts the program and listens for the debugger. The `--inspect-brk` does the same thing except that it automatically breaks on the first line of the program. 12 | 13 | When a process is in debug mode, you can attach to it with browser dev tools to provide a robust debugging experience. 14 | 15 | ## Using the browser dev tools 16 | 17 | This should work in any Chromium based browser - including Chrome itself and Microsoft Edge. 18 | 19 | First, make sure the `app.ts` file contains the following code as we left it in the last module. 20 | 21 | ```typescript 22 | const message: String = Deno.args[0]; 23 | console.log(`Hello ${message}`.toUpperCase()); 24 | ``` 25 | 26 | Run the program as you normally would, but this time, pass in the `--inspect` flag. 27 | 28 | ```bash 29 | deno run --inspect app.ts World 30 | ``` 31 | 32 | Passing the `--inspect` flag opens the debugger port. However, the program runs to completion and you don't have a chance to debug it. This is because you haven't set any breakpoints and your code has no errors. The solution to this is to use the `--inspect-brk` flag instead. 33 | 34 | Run the program again, this time passing in the `--inspect-brk` flag. 35 | 36 | ```bash 37 | deno run --inspect-brk app.ts World 38 | ``` 39 | 40 | This time, the program runs, and then pauses. Now you can attach your browser developer tools to the running program. 41 | 42 | ## Attach with browser dev tools 43 | 44 | > Note that this requires a Chromium-based browser such as Chrome or Edge 45 | 46 | All you need here is an open browser tab. Navigate to `chrome://inspect` or `edge://inspect`. Both will work. In Edge, typing `chrome://inspect` will take you to `edge://inspect`. 47 | 48 | The browser should automatically see your running program and list it as a "target" as shown below. Click the "inspect" link. 49 | 50 | ![The chrome inspect page](../images/edge-inspect.jpg) 51 | 52 | This will open the browser dev tools and you will see the your program is broken on the first line. 53 | 54 | ![The chrome dev tools](../images/chrome-debug.jpg) 55 | 56 | Step over to the next line and hover over the `Deno.args` object. You can see the "World" argument that was passed in. 57 | 58 | ![Hovering over the args argument in Deno](../images/chrome-hover-args.jpg) 59 | 60 | Click the continue button to finish execution and then close the Dev Tools. 61 | 62 | > Note that at the time of this writing, this does not work with WSL2 as Chrome/Edge looks for Deno source code in //home/, which is not a valid path on Windows. 63 | 64 | ## Debugging with VS Code 65 | 66 | The Deno extension for VS Code includes a debugger. It also knows how to automatically configure a `launch.config` with the correct settings to launch the program with `--inspect` and attach the VS Code debugger. 67 | 68 | - Press F1 to open the Command Palette in VS Code 69 | - Type "launch" and select "Open launch.json" 70 | - Select "Deno" 71 | 72 | VS Code creates a launch configuration and adds a file called `launch.json` and a folder called ".vscode". By default, the configuration looks for a file called `main.ts`. But in the exercise, we have called the file `app.ts`. Modify the `launch.config` file so that the `program` is `app.ts`. 73 | 74 | ```json 75 | ..., 76 | "program": "app.ts", 77 | ..., 78 | ``` 79 | 80 | - Open the `app.ts` file. 81 | - Click in the gutter next to line 1 to add a breakpoint. A red circle should appear next to the line. 82 | 83 | ![Breakpoint in VS Code](../images/breakpoint.jpg) 84 | 85 | - Press F5 to start the application. 86 | - The application breaks on the line where you breakpoint is. 87 | - Mouse over the Deno.args object to see the arguments that were passed in. There are none! This is because the debugger is launching the program and you need to pass the argument in there. 88 | 89 | - Press the stop button in the debugger to stop the process. 90 | 91 | - Open the `launch.json` file and add an "args" property underneath the "runtimeArgs" section. 92 | 93 | ```json 94 | "args": [ 95 | "World" 96 | ], 97 | ``` 98 | 99 | > Note that if you added "World" to runtime args, it would be passed BEFORE the name of the file to execute (app.ts) and the command would fail. 100 | 101 | - Press `F5` to run the application again. 102 | - Notice that `Deno.args` now contains "World". 103 | - Press the continue button to finish execution and close the debugger 104 | 105 | Notice that you can't see any output. Why is that? Where is the "Hello World" being logged out to? 106 | 107 | By default, VS Code runs terminal apps on in internal console that you cannot see. You can alter this by specifying the "console" property in the `launch.config` file. Set it to "integrated" to see the output in the VS Code terminal. 108 | 109 | ```json 110 | "args": [ 111 | "World" 112 | ], 113 | "console": "integratedTerminal", 114 | ``` 115 | 116 | - Press F5 to run the application again. 117 | - Press the "step over" button in the debug bar. 118 | - "Hello World" is written to the Integrated Terminal. 119 | 120 | ![Integrated terminal](../images/integrated-terminal.jpg) 121 | -------------------------------------------------------------------------------- /lessons/getting-to-know/arguments-and-flags.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/getting-to-know/arguments-and-flags" 3 | title: "CLI Tour" 4 | order: "3E" 5 | section: "3 - Getting to know Deno" 6 | description: "Burke looks at how to pass arguments and flags to the Deno CLI" 7 | --- 8 | 9 | > Switch to the [3-cli-tour](https://github.com/burkeholland/deno-exercises/tree/3-cli-tour) branch to follow along with this exercise. 10 | 11 | For a full list of arguments you can pass to Deno, execute `deno -h`. 12 | 13 | There are quite a few built-in features for Deno, including a formatter, a linter and a built-in test runner. For any of the built-in arguments, you can select the argument and the pass `-h` again after the argument to find out what you can do with a command, what options are available and what flags you can pass. 14 | 15 | Inspect the `fmt` argument using the `-h` command. 16 | 17 | ```bash 18 | deno fmt -h 19 | ``` 20 | 21 | Change the formatting in the `app.ts` file so that a default value is passed for the message if `args` doesn't exist. Make sure to use single quotes. 22 | 23 | ```typescript 24 | const message: String = Deno.args[0] || "World"; 25 | console.log(`Hello ${message}`); 26 | ``` 27 | 28 | Run the formatter on the `app.ts` file 29 | 30 | ```bash 31 | deno fmt app.ts 32 | ``` 33 | 34 | Notice that the formatter changes the single-quotes to double-quotes. Formatting in Deno is done by the [dprint library](https://github.com/dprint/dprint) with the default configuration. As of the time of this writing, there is no way to pass a configuration to dprint. My personal preference is to use Prettier and let the editor worry about formatting. The same goes for linting. 35 | 36 | ## Passing in Arguments 37 | 38 | Arguments can be passed to the Deno CLI after the path of the file to be executed. 39 | 40 | ```bash 41 | deno run app.ts a b c 42 | ``` 43 | 44 | These arguments are referenced within the file by looking at the `Deno.args` object. 45 | 46 | Modify the code in "app.ts" to log out all incoming arguments... 47 | 48 | ```typescript 49 | console.log(Deno.args); 50 | ``` 51 | 52 | Run the code from the terminal. Pass in the values a, b and c as args 53 | 54 | ```bash 55 | deno run app.ts a b c 56 | 57 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 58 | [ "a", "b", "c" ] 59 | ``` 60 | 61 | Modify the code to echo out the value of the argument passed in and concatenate it with "Hello" 62 | 63 | ```typescript 64 | const message: string = Deno.args[0]; 65 | console.log(`Hello ${message}`); 66 | ``` 67 | 68 | Run the program 69 | 70 | ```bash 71 | deno run app.ts World 72 | 73 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 74 | Hello World 75 | ``` 76 | 77 | Deno doesn't do named arguments by default, but these can be passed in as flags using the Standard Library, which we'll examine later on in this course. 78 | 79 | ## Flags 80 | 81 | Deno has built-in flags that can be passed to the runtime. You've already used many of them. We used "--no-check" to skip TypeScript checking and the "--allow-env" and "--allow-read" permissions flags. 82 | 83 | Flags that are passed to Deno **must** be passed **before** the name of the file to execute. If they are passed after, they will be ignored. This is important as it can cause quite a bit of confusion if your flags are working the way you think they will. 84 | 85 | There are several flags listed from the help, but let's take a look at a few of the ones you will use the most often. 86 | 87 | ### --watch & --unstable 88 | 89 | One of my favorite features of Deno is the built-in watcher. It's kind of like supervisor or nodemon if you've used Node before. It just watches for file changes and then re-builds your TypeScript and restarts the process. 90 | 91 | - Execute the `app.ts` file with the built-in watcher by passing the `--watch` flag. 92 | 93 | ```bash 94 | deno run --watch app.ts World 95 | 96 | error: The following required arguments were not provided: 97 | --unstable 98 | 99 | USAGE: 100 | deno run ... --unstable --watch 101 | 102 | For more information try --help 103 | ``` 104 | 105 | Uh oh - what happened? The CLI is telling us that we are missing a required flag to use the `--watch` feature. That is the `--unstable flag`. The `--unstable` flag allows Deno to run with still unstable features. Watch is one of those features. You'll encounter quite a few features in Deno (which is considered stable) that are behind the "unstable" flag at the time of this writing. That's important to note since you might assume that Deno being "stable" means all of it is stable. That's not the case. 106 | 107 | - Run the program again with the `--unstable --watch` flags... 108 | 109 | ```bash 110 | deno run --unstable --watch app.ts World 111 | 112 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 113 | Hello World 114 | Watcher Process terminated! Restarting on file change... 115 | ``` 116 | 117 | Modify the code in "app.ts" so that it transforms the output to uppercase 118 | 119 | ```bash 120 | const message: String = Deno.args[0]; 121 | console.log(`Hello ${message}`.toUpperCase()); 122 | ``` 123 | 124 | Save the file and notice that the terminal updates with the new output 125 | 126 | ```bash 127 | Watcher File change detected! Restarting! 128 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 129 | HELLO WORLD 130 | Watcher Process terminated! Restarting on file change... 131 | ``` 132 | 133 | ## Others 134 | 135 | There are other flags that can be passed in that deal with different aspects that are unique to Deno. We will take a closer look at these flags when we talk about concepts like dependencies and permissions. For now, the important things to know about the Deno CLI are... 136 | 137 | 1. Pass -h after any option to see a description, sample usage and sub-options 138 | 1. Pass in all flags **before** the file name 139 | 1. Pass in your own arguments **after** the file name 140 | -------------------------------------------------------------------------------- /lessons/what-is/dependencies.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/what-is/dependency-hell" 3 | title: "Dependency Hell" 4 | order: "2C" 5 | description: "Burke looks at what the current state of dependencies in Node.js is, and why Deno has a fundamentally different approach." 6 | section: "2 - What is Deno" 7 | --- 8 | 9 | > Switch to the [2-dependency-hell](https://github.com/burkeholland/deno-exercises/tree/2-dependency-hell) branch in the exercises to follow along with this section. 10 | 11 | Dependencies have been a topic of ongoing controversy as long as computers have existed. Across all platforms, all languages, all runtimes. Everywhere. People have different opinions about how dependencies should be resolved, packaged, referenced and the like. Make no mistake, dependencies are hard. 12 | 13 | The reason for this is that dependencies often take dependencies of their own and those dependencies have dependencies. And that just explodes into a million dependencies to do something very simple. And all of those dependencies could have bugs or security flaws. All of which you assume when you bring them into your project. The dependency manager's job, then is to keep track up what version of what package works with what other package so that if one of those dependencies down the chain gets updated, the whole project doesn't break. You may be familiar with the `package-lock.json` or `yarn.lock` files? That's exactly what those files are doing. 14 | 15 | So what's wrong with the way that Node.js handles dependencies? Well, there are a few things that... maybe could be handled differently. 16 | 17 | ## npm and Single Points of Failure 18 | 19 | First off, npm is the central package repository for Node. Yes, technically anyone can setup a package repository and you can have private ones as well. But by and large, nearly the entire community is served by npm. Is that a bad thing? Maybe, maybe not. 20 | 21 | You may recall that last year there was some escalating issues with npm as it tried to generate enough revenue to stay afloat. Serving up packages to everyone in the world is an expensive endeavor. I don't know if you've ever looked at cloud bandwidth bills, but they are frequently the lions share of cloud computing costs. And npm is absorbing that every day. GitHub stepped in and purchased npm earlier this year, possibly preventing what could have been the collapse of essentially where all our Node packages live. 22 | 23 | Again, is a single package repository a bad thing? Maybe not. It's incredibly convenient to have a central place to look for any code you might want to use and not have it strewn about over the internet. It's probably a driving force behind why Node's adoption was so quick as well. 24 | 25 | But for that convenience we get a single point of failure and it is now owned by a corporation. Some people may not feel great about those two realities. 26 | 27 | ### package.json 28 | 29 | Believe it or not, one of the things that Ryan regrets is the `package.json` file. I find this to be a nitpick, but he feels like it's a lot of boilerplate and for what? He's got a point there. 30 | 31 | In the "exercise" folder, execute the following command... 32 | 33 | ```javascript 34 | npm init 35 | ``` 36 | 37 | You get asked about a dozen questions and it's not clear why you need any of this information. What's an entry point? Do you need one? Why do you need a version? Keywords? These things might be important if you are creating an npm package, but most of us are not doing that. The `package.json` is usually full of information that you don't really need. It's extraneous. 38 | 39 | ```json 40 | { 41 | "name": "2-dependency-hell", 42 | "version": "1.0.0", 43 | "description": "", 44 | "main": "index.js", 45 | "scripts": { 46 | "test": "echo \"Error: no test specified\" && exit 1" 47 | }, 48 | "keywords": [], 49 | "author": "", 50 | "license": "ISC" 51 | } 52 | ``` 53 | 54 | Now, it should be noted that you can execute the shorthand... 55 | 56 | ```javascript 57 | npm init -y 58 | ``` 59 | 60 | Which won't ask you any questions, but still gives you the same output. 61 | 62 | This is not necessarily a bad thing. The `package.json` file lets you specify a lot of metadata that a lot of libraries do use. For instance, when you publish a VS Code extension, it needs some fields in that `package.json` in order to fill out the page for your extension correctly. 63 | 64 | One last point about the `package.json` is that it contributes to the bloat of configuration files in a repo. Just look at the number of config files in the static site code for this course... 65 | 66 | ![static site dependencies](../images/static-site-deps.jpg) 67 | 68 | ## node_modules 69 | 70 | The node_modules folder has become notorious for being exceptionally large. You have no idea how many dependencies you are getting yourself into, and these folders often balloon to a laughable size. 71 | 72 | In the folder where you initialized a project, run the following command to install the common axios web request package... 73 | 74 | ```bash 75 | npm i axios 76 | ``` 77 | 78 | Examine the node_modules folder. You'll see that you get "axios", and "follow-redirects". I'm not exactly sure why axios needs that, but I don't have a problem with it taking only one dependency. 79 | 80 | Now try this - install "react-scripts", the package the create-react-app uses... 81 | 82 | ```bash 83 | npm i react-scripts 84 | ``` 85 | 86 | This is going to take a while, and when it's done, you'll see that your node_modules folder has grown to around 302 MB. That's....a lot. This is not a shot at React. It is not alone in requiring what seems like an inappropriate amount of dependencies just to build a website. 87 | 88 | In cases where you need to deploy a Node.js app to run on a server, the entire node_modules folder needs to be there as well. This requires an `npm install` to happen on the server, or on a build server and all the assets copied in. In his talk, Ryan mentions that his primary hang-up with this is that the build asset should be an executable - kind of like a .exe. Instead of needing thousands of files to run a project. 89 | -------------------------------------------------------------------------------- /lessons/oak/oak-templates.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/oak/oak-templates" 3 | title: "Templates" 4 | order: "7D" 5 | section: "7 - Oak web framework" 6 | description: "Burke introduces the Oak web framework for Deno" 7 | --- 8 | 9 | > Make sure you are on the [7-oak-templates](https://github.com/burkeholland/deno-exercises/tree/7-oak-templates) branch to follow along with this section. 10 | 11 | A key benefit of web servers is being able to dynamically compose templates. In order to do that with Oak, we need to add a templating engine. In this section, we'll add the templating engine and change the router to render the template instead of just text. 12 | 13 | ## Finding a template engine 14 | 15 | Deno has a surprising amount of third-party libraries to choose from given how new it is. If we [search Deno's third party registry](https://deno.land/x?query=template) for template libraries, we see there are quite a few to choose from. This includes some well known libraries like Mustache and Handlebars. Given that I usually opt for Handlebars with Express, we'll be using that one for this Oak project. 16 | 17 | ![](../images/deno-templates.jpg) 18 | 19 | > Note that there are "view engines" for Deno. We won't be using any of those options in this workshop because I felt like they inject too much complexity into the conversation. Libraries like the "view_engine" project do provide some enhanced functionality, such as caching. 20 | 21 | If you click on the "handlebars" option, you'll see the README which shows the URL that you'll need to import. 22 | 23 | ![](../images/handlebars-readme.jpg) 24 | 25 | ## Import Handlebars into the Oak project 26 | 27 | First, we need to import the Handlebars library into our "deps.ts" file. Don't forget to export it at the bottom as well! 28 | 29 | ```typescript 30 | import { Application, Router } from "https://deno.land/x/oak/mod.ts"; 31 | import { Handlebars } from "https://deno.land/x/handlebars/mod.ts"; 32 | 33 | export { Application, Router, Handlebars }; 34 | ``` 35 | 36 | > I find it interesting that while Deno aims to avoid centralizing dependencies, it has effectively done so by creating this repository at deno.land/x. We may very well see npm again by another name. 37 | 38 | To use the Handlebars library, we need to initialize an instance and pass in some configuration. To do this, we'll create a shared object that the routers can import and then use to return template rendered views. Even though we're importing a file that called "new" multiple times, the same instance should be reused as it is cached by the runtime. 39 | 40 | Let's create a root folder called "shared" and add an "hbs.ts" file inside. In that file, we'll need to import the Handlebars dependency from our "deps.ts" file. 41 | 42 | ```typescript 43 | import { Handlebars } from "../deps.ts"; 44 | ``` 45 | 46 | Create a new instance of the Handlebars class and pass in the following configuration object. Export the new instance. 47 | 48 | ```typescript 49 | import { Handlebars } from "../deps.ts"; 50 | 51 | const handlebars = new Handlebars({ 52 | baseDir: "views", 53 | extname: ".hbs", 54 | layoutsDir: "layouts/", 55 | partialsDir: "", 56 | defaultLayout: "main", 57 | helpers: undefined, 58 | compilerOptions: undefined, 59 | }); 60 | 61 | export default handlebars; 62 | ``` 63 | 64 | These options are all the defaults with the exception of the empty string for the `partialsDir` option. This is because we won't be using partial views for this course and if we don't override the default value (`partials/`), a "file not found" error will be thrown by the Handlebars library. 65 | 66 | Before we can actually use these templates, we need to create them. Create a new folder in the exercise project root called "views". First, we need a Layout. A Layout is the shell of the page. It is the main HTML page into which all of our other files will be rendered. Add a "layouts" folder to the "views" directory. Create a "main.hbs" file in the "views/layouts" directory, and add the following markup. 67 | 68 | ```html 69 | 70 | 71 | 72 | 73 | 74 | Oak 75 | 76 | 77 | {{{ body }}} 78 | 79 | 80 | ``` 81 | 82 | This file serves as the main layout template. The `{{{ body }}}` is where we'll render different views depending on which URL is requested. 83 | 84 | Now we need an "index" template to correspond with our "/" (index) route. We'll be passing in a "title" to the template from our code. Create an "index.hbs" file in the "views" folder and add the following markup. 85 | 86 | ```html 87 |

{{ title }}

88 |

Welcome to {{ title }}

89 | ``` 90 | 91 | This fragment will be rendered where the `{{{ body }}}` tag is in the "main.hbs" file. 92 | 93 | Last, we need to render our templates and tell Oak to return them as the response. To do that, we first need to import the shared "hbs.ts" file into the "indexRoutes.ts" file. 94 | 95 | ```typescript 96 | import { Router } from "../deps.ts"; 97 | import hbs from "../shared/hbs.ts"; 98 | ``` 99 | 100 | Now, instead of returning text to the `ctx.response.body`, call the `hbs.renderView` method. You'll need to pass in the name of the template that you want to render (index) and any data that the template needs. In our case, it's just a "title" property. 101 | 102 | ```typescript 103 | import { Router } from "../deps.ts"; 104 | import hbs from "../shared/hbs.ts"; 105 | 106 | export function use(path: string, router: Router) { 107 | router.get(`${path}`, async (ctx) => { 108 | ctx.response.body = await hbs.renderView("index", { title: "Oak" }); 109 | }); 110 | } 111 | ``` 112 | 113 | Now run the application again and see what you get. 114 | 115 | ![application running returning template](../images/app-with-templates.jpg) 116 | 117 | OK! Not super impressive to look at, but we're now handling routing and returning dynamic templates. The next thing we need to do is style this page with some CSS. To do that, we need to figure out how to get Oak to return static files from a directory in our project. That's exactly what we'll do in the next section. 118 | 119 | **Bonus** - Create a "users" template and handle the view rendering in the "userRoutes.ts" file. 120 | -------------------------------------------------------------------------------- /lessons/welcome/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/intro" 3 | title: "Introduction" 4 | order: "1A" 5 | section: "1 - Welcome" 6 | description: "Burke covers the agenda for the Deno First Look workshop, talks about himself a little bit more than you would probably like, explains how to submit issues with this course and then pontificates on whether or not Deno is something that has a future and if we should be investing valuable time into learning it." 7 | --- 8 | 9 | Welcome to Deno First Look! 🎉 10 | 11 | ## Course Objective 12 | 13 | The objective of this course is to help you understand what Deno is, why on earth we need yet another JavaScript runtime (isn't Node.js good enough?), and how to build applications with Deno. Depending on when you see this, Deno may or may not have gained enough popularity in the JavaScript community to be prolific. The truth is we don't know if it will. But going through this course will ensure that you are not caught on your heels if it does. Either way, it just might open your mind to considering a different JavaScript runtime than what you may be used to. 14 | 15 | ## Who Are You? 16 | 17 | You should be a JavaScript developer with knowledge of Node.js. It's likely that if you're doing JavaScript development these days, that's a given. Node.js is used by most people in at least a development capacity - running local web servers, linting tools, ect. If you are using Node.js in production to host applications such as websites, web services, APIs, microservices, ect, then this course is especially applicable to you. Many of the exercises we'll go through in this course will specifically compare to functionality or libraries that exist today in Node. 18 | 19 | Knowledge of TypeScript is also a plus, but not required. We don't spend a lot of time getting into types or messing with TypeScript paticulars like interfaces, modules or the compiler details. There is quite a bit of that in Deno, but my feeling is that it adds a layer of confusion that isn't necessary to understand and be productive with Deno. It's also extremely off-putting if you don't know TypeScript, and I don't want to put you off. I want to excite you. 20 | 21 | If you would like to get a general knowledge of what TypeScript is, refer to [this video](https://channel9.msdn.com/posts/Anders-Hejlsberg-Introducing-TypeScript), which should be sufficient knowledge for this course. Normal JavaScript works just fine in TypeScript, and Deno supports both so I wouldn't worry too much about it. 22 | 23 | ## Where To File Issues 24 | 25 | The last time I did a course, I got a lot of PR's on mistakes made throughout. Most were grammatical or wrong images. There was a lot of misuse of "it's" vs "its". English is hard. Furthermore, my attention to detail isn't what it should be. What I'm trying to say is that mistakes in this course are inevitable, and I know that you will see what I cannot. If you do, I would love it if you would [open a pull request](https://github.com/burkeholland/deno-first-look/pulls) or [file an issue](https://github.com/burkeholland/deno-first-look/issues) on the GitHub repo. You can always find me on Twitter as well, although I try to avoid social media because I want to be happy so replies will be _seriously_ delayed. 26 | 27 | ## Who Am I? 28 | 29 | ![Yours truly at the Badlands in South Dakota](../images/me.jpg) 30 | 31 | My name is Burke Holland, and I am a Content Engineer at Microsoft, where I do advocacy around VS Code, GitHub, Azure and all things JavaScript. I have a cursor on my face. 32 | 33 | I work with a team of great people and together we try and make Microsoft tools, services, and runtimes the best place in the world for JavaScript developers. I've been a JavaScript developer for 12 years. That's a long time in the world of JavaScript. I first fell in love with it when jQuery came out, and I have never looked back. I love everything about JavaScript, and I've never tired of writing it. I think it's a magical language that is uniquely easy to get started with and bizarrely well suited for applications of all types. 34 | 35 | I love teaching because it's simply the best way to learn anything. It also lets me connect with people and through this, I have learned that we are all far more alike than we are different. Mainly, we are all learning, and nobody has it all figured out. If you feel like you are the only one who doesn't understand things, let me assure you, you are not. There are at least 2 of us, and I am one. I love this diagram. I think it says it all. 36 | 37 | ![](../images/what-i-know.png) 38 | 39 | _Image Credit:_ [Alicia Liu](https://medium.com/counter-intuition/overcoming-impostor-syndrome-bdae04e46ec5) 40 | 41 | I live in Nashville with my wife, 3 teenage boys and 2 pugs. I'm a huge fan of Overwatch and I main Wrecking Ball. I know a lot of people don't like Wrecking Ball and they tell me all the time when we lose. I'm also an amateur craftsman, having built several pieces of modest furniture and doing remodel projects when my wife has new ideas for the house. There is a lot in common with woodworking and coding. Or knitting and coding. If you like coding, try picking up a different craft. Because you _are_ a craftsman. 42 | 43 | If you'd like to connect, you can [find me on Twitter](https://twitter.com/burkeholland). Although I treat Twitter kind of like Walmart - I only go in if I absolutely have to, so a better place to catch me is to [email me directly](mailto:burkeholland@gmail.com). I'd love to hear from you! 44 | 45 | ## Why Was This Course Created? 46 | 47 | ![Frontend Masters Logo](../images/FrontendMastersLogo.png) 48 | 49 | I think the key to staying sane in this industry is to always be open to learning new things. It's also good to learn to learn-and-forget. You'll pick up things that stay with you and pay dividends down the road. Deno may be a ripple in a vast and endless ocean of JavaScript projects, libraries and frameworks. Or it may become the ocean itself. We don't know and that can cause distress. Learning about something removes the fear and intimidation that causes us to avoid things. This is true for everything in life, not just technology. Try it out and you'll see what I mean. If something scares you, learn more about it and will lose its power. 50 | 51 | There is also no idea that should be off the table when it comes to technology. Let's look at them all and pick the ones that work best for you, your brain, your team and your project. 52 | 53 | I have a [Frontend Masters course on VS Code](https://frontendmasters.com/courses/customize-vs-code/) as well if you'd like to check that out. That's a completely free course available to everyone. No subscription required. 54 | 55 | Thanks for staying with me, and I hope you enjoy this course: Deno First Look. 56 | -------------------------------------------------------------------------------- /lessons/what-is/secure-by-default.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/what-is/secure-by-default" 3 | title: "Secure By Default" 4 | order: "2B" 5 | description: "Deno runtime is secure by default. This is in stark contrast to how Node works today, and it's important to understand why so that Deno's default locked down state doesn't feel so oppressive." 6 | section: "2 - What is Deno" 7 | --- 8 | 9 | > Switch to the [2-secure-by-default](https://github.com/burkeholland/deno-exercises/tree/2-secure-by-default) branch in the exercises to run the code in this section 10 | 11 | Deno is secure by default. When I hear things like this, they often come off to me as esoteric and frankly paranoid reasons to write an entirely new runtime. The truth is, though, that Node.js is not a secure runtime environment. When you run a Node program on your local machine, it has all the permissions that you do. If you have the write to access a file, so does that program. And most of us as developers are have root or admin access on our own machines. Even if we don't, it would be fairly easy for an npm module with bad intentions to do some nasty damage to your machine, or worse, your production environment. 12 | 13 | The browser is not like this. The browser is a secure sandbox that has zero access to your machine unless you grant it. Your phone is the same way. Think about it. Can apps on your phone access your location without your permission? Can they access your files and photos? No. You have to explicitly grant them the rights to do this. 14 | 15 | Similarly, the browser needs rights to access you location or camera, or even permission to send you a notification. 16 | 17 | But look at how this plays out in Node... 18 | 19 | The Node fs module lets you read and write to the file system. This means that you can pretty easily read sensitive information with the "fs" module - maybe something like this: 20 | 21 | ```javascript 22 | const fs = require("fs").promises; 23 | const path = require("path"); 24 | const homedir = require("os").homedir(); 25 | 26 | async function findEnvFiles(folderName, envFiles) { 27 | // read all the items in the current folder 28 | const items = await fs.readdir(folderName, { withFileTypes: true }); 29 | 30 | // iterate over each found item 31 | for (item of items) { 32 | // if the item is a directory, it will need to be searched 33 | if (item.isDirectory()) { 34 | // call this method recursively, appending the folder name to make a new path 35 | await findEnvFiles(path.join(folderName, item.name), envFiles); 36 | } else { 37 | // Make sure the discovered file is a .env file 38 | if (item.name === ".env" || item.name.indexOf(".env.") > -1) { 39 | // store the file path in the envFiles array 40 | envFiles.push(path.join(folderName, item.name)); 41 | } 42 | } 43 | } 44 | } 45 | 46 | async function readSecrets(envFiles) { 47 | let allSecrets = []; 48 | for (file of envFiles) { 49 | const secrets = await (await fs.readFile(file)).toString(); 50 | allSecrets.push(secrets); 51 | } 52 | return allSecrets; 53 | } 54 | 55 | async function main() { 56 | const envFiles = []; 57 | await findEnvFiles(homedir, envFiles); 58 | 59 | const secrets = await readSecrets(envFiles); 60 | 61 | secrets.forEach((secret) => { 62 | console.log(secret); 63 | }); 64 | } 65 | 66 | main(); 67 | ``` 68 | 69 | This code recursively reads your home directory for anything that looks like an .env file, and then logs that out. That's all your secrets, connection strings, etc. If I can get you to run this, then I can get your database connection strings, your OAuth keys - whatever you might be keeping in those local .env files. 70 | 71 | But how do I get you to run this? Aren't you smart enough NOT to run some package you don't trust or code that just looks nefarious? After all, YOU have to run this. So how do I get you to run it? 72 | 73 | The open-source world is such a wonderful place in which nobody would ever take advantage of you, right? Fortunately, that is by and large true, but by definition, open-source is open. Anyone can publish a module to npm. There is no review process. There is no security scan that occurs. Publish to npm and that module is immediately live for anyone to consume. So I could stick that code into an npm module and immediately make it available for anyone. But again, how do I get you to install and run this module? 74 | 75 | In his talk entitled, "How to hack a Node.js app", Asim Houssain details the extent to which the Node ecosystem is routinely used to exploit, hijack and otherwise maliciously execute code on unsuspecting machines. 76 | 77 | 78 | 79 | In this talk, he mentions many different ways that exploits can be done. But one of the most common and malicious is so simple that it's disappointing. 80 | 81 | ### Typo Squatting 82 | 83 | Typo squatting is when a package names itself in a commonly mistyped form of a legitimate module. In his talk, Wassim gives the example of the "crossenv" package. The "crossenv" package is a commonly used utility that normalizes the passing in of command line flags across Windows and Linux. It is widely used. Someone figured out that people commonly try to install "cross-env" instead of "crossenv" because they aren't sure what the exact name of the package is. One of those packages normalizes how programs are launched, the other reads your .env files - you know - where all your secrets and keys are stored and sends them to a remote server. WHICH IS EXACTLY WHAT THE CODE ABOVE DOES. 84 | 85 | Now that's pretty bad, but it can get much, much worse. 86 | 87 | In preparing for this course, I ran across a headline from zdnet... 88 | 89 | ![](../images/zdnet.jpg) 90 | 91 | "You should consider your entire system compromised". 92 | 93 | That's heavy. And it can happen to anyone. And if you read that article, it says that even uninstalling the module doesn't mean you are safe. Because who knows what these packages installed and ran in the background? 94 | 95 | Node.js is simply not a safe runtime. It is wide open and is based on a wide open package system. While that makes is super convenient to use, it is by definition also relatively easy for seriously bad things to happen to your programs, even when you are paying close attention. There is a direct trade-off between convenience and security. Node has optimized for convenience. 96 | 97 | Deno is secure by default. That means that by default, programs have no access to read your file system, make an http call or perform other I/O related activities on your machine. You have to explicitly grant it access. We'll see how this works when we get into the syntax of Deno. You'll also get to see this tradeoff of convenience in action and decide for yourself whether or not "secure by default" should in fact be the default. 98 | 99 | Now this doesn't guarantee that you will be safe, but it makes it much harder for you to be victimized. It starts from a position of safety, and then asks you to opt out of that. Secure by default. 100 | -------------------------------------------------------------------------------- /lessons/oak/oak-router.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/oak/oak-router" 3 | title: "The Oak Router" 4 | order: "7C" 5 | section: "7 - Oak web framework" 6 | description: "Burke introduces the Oak web framework for Deno" 7 | --- 8 | 9 | > Make sure you switch to the [7-oak-router](https://github.com/burkeholland/deno-exercises/tree/7-oak-router) branch to follow along with this section. 10 | 11 | Oak contains prebuilt Router middleware that will allow you to handle different routes, parameters and queries. It's basically doing a lot of string parsing and pattern matching that you would otherwise have to do yourself. 12 | 13 | Include the "Router" object in the Oak import. 14 | 15 | ```typescript 16 | import { Application, Router } from "https://deno.land/x/oak/mod.ts"; 17 | ``` 18 | 19 | Create a new "Router" instance below the "Application" instance. 20 | 21 | ```typescript 22 | const app = new Application(); 23 | const router = new Router(); 24 | ``` 25 | 26 | Create a handler for a "GET" request to "/" - or the root route. 27 | 28 | ```typescript 29 | import { Application, Router } from "https://deno.land/x/oak/mod.ts"; 30 | 31 | const app = new Application(); 32 | const router = new Router(); 33 | 34 | router.get("/", (ctx) => { 35 | ctx.response.body = "Welcome to Oak"; 36 | }); 37 | ``` 38 | 39 | Tell the `app` object to use the `router` as middleware. 40 | 41 | ```typescript 42 | import { Application, Router } from "https://deno.land/x/oak/mod.ts"; 43 | 44 | const app = new Application(); 45 | const router = new Router(); 46 | 47 | router.get("/", (ctx) => { 48 | ctx.response.body = "Welcome to Oak"; 49 | }); 50 | 51 | app.use(router.routes()); 52 | 53 | console.log(`Now listening on http://0.0.0.0:3000`); 54 | await app.listen("0.0.0.0:3000"); 55 | ``` 56 | 57 | Run the app with `deno run --allow-net app.ts` 58 | 59 | You should see the same thing you had before - a simple page saying "Welcome to Oak". Note, though, that this route will only respond to the root route, and only if the request is a GET. Before, the application would respond to any request at all. 60 | 61 | ## Adding additional routes 62 | 63 | Add an additional "users" route that responds to the "/users" route. It should come before the `app.use(router.routes())` line. 64 | 65 | ```typescript 66 | router.get("/", (ctx) => { 67 | ctx.response.body = "Welcome to Oak"; 68 | }); 69 | 70 | router.get("/users", (ctx) => { 71 | ctx.response.body = `Welcome User`; 72 | }); 73 | ``` 74 | 75 | Add a third route which also listens to the "/users" route, but listens for an additional "/:name" param and echoes the value back out. 76 | 77 | ```typescript 78 | router.get("/", (ctx) => { 79 | ctx.response.body = "Welcome to Oak"; 80 | }); 81 | 82 | router.get("/users", (ctx) => { 83 | ctx.response.body = `Welcome User`; 84 | }); 85 | 86 | router.get("/users/:name", (ctx) => { 87 | ctx.response.body = `Welcome ${ctx.params.name}`; 88 | }); 89 | ``` 90 | 91 | Run the application again and test the different routes. Try passing in "localhost:3000/users/YOUR_NAME". It should be echoed back out to you. 92 | 93 | ## Organizing routes like Express 94 | 95 | The Express generator puts all the routes in files that correspond to their base route. For instance, the "/" routes are contained in the "routes/index.js" file. The "/user" routes are all contained in the "routes/users.js" file. In this section, you'll refactor your code to move the routes into their own folder. 96 | 97 | ### Creating a deps.ts file 98 | 99 | In order to do that, we're going to need to access our dependencies from more than one file. Instead of importing URL's all over the application, let's move all our imports into a single "deps.ts" file. 100 | 101 | - Cut the Oak import line from the top of the "app.ts" file. 102 | - Create a file in the root called "deps.ts" 103 | - Paste in the Oak import 104 | - Export the `Application` and `Router` objects. 105 | 106 | ```typescript 107 | import { Application, Router, Context } from "https://deno.land/x/oak/mod.ts"; 108 | export { Application, Router, Context }; 109 | ``` 110 | 111 | In the "app.ts" file, import the `Application` and `Router` objects from the "deps.ts" file 112 | 113 | ```typescript 114 | import { Application, Router } from "./deps.ts"; 115 | ``` 116 | 117 | ### Creating routes files 118 | 119 | Right now, all of the routes are in the main `app.ts` file. This is fine when we only have 3 routes, but what happens when we have 100? A better solution would be to have one file per "route". 120 | 121 | For instance, we can create a file that handles all requests to "/". It doesn't matter if they are a GET, POST, PUT or if the path has a parameter on it, we can put all of that logic in a single file. 122 | 123 | - Create a folder called "routes" 124 | - Create a file called "indexRouter.ts" in the "routes" folder. 125 | - Import the "Router" object from the "deps.ts" file 126 | 127 | ```typescript 128 | import { Router } from "../deps.ts"; 129 | ``` 130 | 131 | Create a function called "use" which will accept a path and a reference to the router object. This will allow us to pass in the path we want this function to handle as well as the router object we defined in the `app.ts` file. 132 | 133 | ```typescript 134 | import { Router } from "../deps.ts"; 135 | 136 | export function use(path: string, router: Router) {} 137 | ``` 138 | 139 | Move the index route to this new "indexRouter.ts" file 140 | 141 | ```typescript 142 | import { Router } from "../deps.ts"; 143 | 144 | export function use(path: string, router: Router) { 145 | router.get(`${path}`, async (ctx: Context) => { 146 | ctx.response.body = "Welcome to Oak"; 147 | }); 148 | } 149 | ``` 150 | 151 | We use the "path" variable and append all routes to that object. That's so that we can specify the path in the "app.ts" file for all our routers. As we add more and more routers, it's going to be important to know what router is handling what path by just by looking at the "app.ts" file. 152 | 153 | Import the new file as `indexRouter` at the top of the "app.ts" file 154 | 155 | ```typescript 156 | import { Application, Router } from "./deps.ts"; 157 | import * as indexRouter from "./routes/indexRouter.ts"; 158 | ``` 159 | 160 | Tell the router to the "/" path and the existing "router" object. 161 | 162 | ```typescript 163 | indexRouter.use("/path", router); 164 | ``` 165 | 166 | Run the app again to make sure the index route still works. 167 | 168 | Repeat the same thing for the "user" routes with a file called "routes/userRouter.ts". Your final "app.ts" should look like this... 169 | 170 | ```typescript 171 | import { Application, Router } from "./deps.ts"; 172 | import * as indexRouter from "./routes/indexRouter.ts"; 173 | import * as userRouter from "./routes/userRouter.ts"; 174 | 175 | const app = new Application(); 176 | const router = new Router(); 177 | 178 | indexRouter.use("/", router); 179 | userRouter.use("/users", router); 180 | 181 | app.use(router.routes()); 182 | 183 | console.log(`Now listening on http://0.0.0.0:3000`); 184 | await app.listen("0.0.0.0:3000"); 185 | ``` 186 | 187 | Now that we've got a proper routing structure in place, let's turn our attention to the next big problem to solve - and that's how to use templates to return HTML instead of just returning text. 188 | -------------------------------------------------------------------------------- /lessons/webserver/reading-parameters.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/webserver/reading-parameters" 3 | title: "Reading the query string" 4 | order: "6B" 5 | section: "6 - Building a Webserver" 6 | description: "Burke looks at how to build a simple web server with Deno" 7 | --- 8 | 9 | > Make sure you are on the [6-reading-the-query-string](https://github.com/burkeholland/deno-exercises/tree/6-reading-the-query-string) branch to follow along with this section. 10 | 11 | ## Reading query parameters 12 | 13 | An important part of any web server is the ability to handle parameters. These could be query string parameters or parameters passed on the body. Let's look at how to do both of those things with our simple web server. 14 | 15 | Let's modify this app so that it returns a "Hello" when we pass in a `name` parameter on the query string. Like this... 16 | 17 | ```bash 18 | http://localhost:3000?name=World 19 | ``` 20 | 21 | How do we get that "name" parameter? Well, we need to parse the query string to do that. The Deno web server is just that, and it doesn't come with an easy way to just get the query string parameters. But we can get them from the request. 22 | 23 | The `req.url` object holds the URL fragment - which is everything that comes after the address and port. You can use the browser [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) object to parse out the query string parameters. 24 | 25 | > Note that a "/" gets prepended to the "?" in a query string by the browser and URLSearchParams can't handle this. So we'll strip off the first character with substring(). 26 | 27 | In the for loop, use the `URLSearchParams` object to parse the `req.url` and get the name. 28 | 29 | ```typescript 30 | for await (const req of server) { 31 | const searchParameters = new URLSearchParams(req.url.substring(1)); 32 | const name = searchParameters.get("name"); 33 | 34 | req.respond({ 35 | body: "

Hello World

", 36 | }); 37 | } 38 | ``` 39 | 40 | Check to the see if the `name` parameter was passed in. If so, return it in the HTML. If not, throw a 500 server error. 41 | 42 | ```typescript 43 | for await (const req of server) { 44 | const searchParameters = new URLSearchParams(req.url.substring(1)); 45 | const name = searchParameters.get("name"); 46 | 47 | if (name) { 48 | req.respond({ 49 | body: `

Hello, ${name}

`, 50 | }); 51 | } else { 52 | req.respond({ 53 | status: 500, 54 | body: "The name parameter was not found on the request", 55 | }); 56 | } 57 | } 58 | ``` 59 | 60 | Run the program... 61 | 62 | ```bash 63 | deno run --allow-net=0.0.0.0:3000 app.ts 64 | ``` 65 | 66 | Pass in the name parameter on the URL... 67 | 68 | ```bash 69 | http://localhost:3000?name=World 70 | ``` 71 | 72 | The browser should return whatever name you pass in. If not, you should get a 500 error with a message saying that a "name" parameter is required. 73 | 74 | ## Route Parameters 75 | 76 | But what about route parameters? Query strings are simple enough, but how can we parse out a route parameter such as `/:name`? We can do that, but we'll need more than what Deno offers with its standard library. And, unfortunately, we'll need more than what we can from it's current third-party library offerings as well. 77 | 78 | But what about npm? 79 | 80 | Let's do a quick check. Yep - looks like there is a package called [route-parser](https://www.npmjs.com/package/route-parser) ready to go that will parse route parameters for us no problem. This is why Node is so great. Every problem is one package install away. Or maybe that's the problem with Node. I'll let you decide. 81 | 82 | In any event, we're going to get a chance to see how we can use Node modules in our program. 83 | 84 | ### Using Node Dependencies 85 | 86 | We can use _some_ Node modules in Deno. If they have strong Node runtime dependencies, they probably won't work. But this one says it's isomorphic. That means that it works in Node and in the browser. If it works in the browser, there is a high probability it will work in Deno. 87 | 88 | But how do we import a Node module into Deno? What is the URL for a Node module. 89 | 90 | There are a few services out there that will allow you to import a package from npm via URL. One of them is called "unpkg". Unfortunately, this won't work for us in Deno and that's because of the fact that Deno only supports ES modules. A lot of Node modules predate that syntax and offer CommonJS `module.exports` syntax. Let's look at this "route-parser" code what it's doing. If you visit the "lib" folder in the repo and look at the ["route.js"](https://github.com/rcs/route-parser/blob/master/lib/route.js) file. The last line says... 91 | 92 | ```javascript 93 | module.exports = Route; 94 | ``` 95 | 96 | That's CommonJS. It's not going to work with Deno. So what do we do? Well, believe it or not there is a service called ["jspm"](https://jspm.org/) which will take a module by URL and give you an ES Module compatible import/export. All we have to do is run this module through that service and it will let us import the module... 97 | 98 | ```typescript 99 | import routeParser from "https://dev.jspm.io/route-parser@0.0.5"; 100 | ``` 101 | 102 | But we've got TypeScript here. Which means we need type definitions to use this library. How do we import those? 103 | 104 | First, the types have to exist. Fortunately for us, searching for "route parser types" in npm will reveal that the ["DefinitelyTyped"](https://definitelytyped.org/) library has [typings for "route parser"](https://www.npmjs.com/package/@types/route-parser). 105 | 106 | We need this file served up raw. In that case, the "unpkg" service will work just fine... 107 | 108 | ```typescript 109 | import routeParser from "https://dev.jspm.io/route-parser@0.0.5"; 110 | import RouteParser from "https://unpkg.com/@types/route-parser@0.1.3/index.d.ts"; 111 | ``` 112 | 113 | Now we just need to tell TypeScript that `routeParser` is type of `RouterParser`... 114 | 115 | ```typescript 116 | import routeParser from "https://dev.jspm.io/route-parser@0.0.5"; 117 | import RouteParser from "https://unpkg.com/@types/route-parser@0.1.3/index.d.ts"; 118 | 119 | const Route = routeParser as typeof RouteParser; 120 | ``` 121 | 122 | And now we can use it just like the "route-parser" docs show. Let's return the name if we find it and if not, return a static "404.html" page. 123 | 124 | ```typescript 125 | import { serve } from "https://deno.land/std/http/server.ts"; 126 | 127 | import routeParser from "https://dev.jspm.io/route-parser@0.0.5"; 128 | import RouteParser from "https://unpkg.com/@types/route-parser@0.1.3/index.d.ts"; 129 | 130 | const Route = routeParser as typeof RouteParser; 131 | 132 | const PORT = 3000; 133 | const HOSTNAME = "0.0.0.0"; 134 | 135 | const server = serve({ hostname: HOSTNAME, port: PORT }); 136 | 137 | console.log(`Server is now running on: http://${HOSTNAME}:${PORT}`); 138 | 139 | const route = new Route("/:name"); 140 | 141 | for await (const req of server) { 142 | const match: any = route.match(req.url); 143 | if (match.name) { 144 | req.respond({ body: `Hello, ${match.name}` }); 145 | } else { 146 | req.respond({ body: "Please pass a name route." }); 147 | } 148 | } 149 | ``` 150 | 151 | As you can see - it's a little hacky. It's not the best solution, but it _does_ work. It also shows you what it's like to import type definitions for a file that isn't TypeScript. 152 | -------------------------------------------------------------------------------- /lessons/deploying/containerize.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/deploying/containerize-deno-app" 3 | title: "Containerizing a Deno Application" 4 | order: "8A" 5 | section: "8 - Deploying" 6 | description: "Burke looks at how to deploy an application built with Deno" 7 | --- 8 | 9 | > Make sure you are on the 8-containerize branch to complete this section. 10 | 11 | ## Prerequisites 12 | 13 | In order to complete this section, you'll need the following installed... 14 | 15 | - [Docker Community Edition](https://docs.docker.com/get-docker/) 16 | - [Docker extension for VS Code](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker&WT.mc_id=devcloud-0000-buhollan) 17 | 18 | A Deno application can be deployed to production in 3 different ways - unbundled, bundled, and compiled. 19 | 20 | ### Bundled, Unbunbled, and Compiled 21 | 22 | Unbundled is what we're working with right now. It's just your project as it is. This is what you would be used to doing with most Node.js projects. 23 | 24 | Bundled is where all of your source code is built into a single .js file that you can deploy. It will run as long as Deno is installed. Unfortunately, at the time of this writing, the bundle command isn't reliable and produces an output - at least for this project where the code is out of order. There is an open issue for this, but it means that we can't deploy this project as a bundle. 😟 25 | 26 | Compiled is very interesting. It compiles your project down into a single executable that will run without Deno. All you need is that executable and nothing else. This is new in 1.6. Caveats are that it isn't cross-platform. You have to compile for the platform you're targeting on that same platform. So if I compile it on Windows, it will not run on Linux and vice-versa. 27 | 28 | Unfortunately - again - the `compile` command appears to use the bundle command, which, as we've discussed, isn't working at the moment for all projects - so we can't use the "compile" either. 29 | 30 | So that leaves us with unbundled. 31 | 32 | The way that you run an unbundled app in production is the same as how you run it in development. For instance, we've been running our Oak web project so far with... 33 | 34 | ```bash 35 | deno run -A --unstable app.ts 36 | ``` 37 | 38 | That same line will be how you run it when you deploy it. Just like any application, you basically have 3 options for deployment with Deno... 39 | 40 | 1. Your server (or VM) 41 | 1. A PaaS 42 | 1. A Container 43 | 44 | Of course, you can always run anything you like on your own server or a server/VM you rent from a cloud hosting provider (hopefully Azure, but you do you). 45 | 46 | A PaaS is short for "Platform as a Service". A PaaS is a hosting provider where you only provide your code. They provide the runtime and handle starting and stopping your application. Heroku is probably the best known for this, although you can find them on Azure App Service, Google Cloud Platform and Amazon Web Services as well. 47 | 48 | Nearly all of these PaaS providers will allow you to run your Deno app on their PaaS. You can find docs for Heroku, Azure and I'm sure many others. Since each one of these is specific to the hosting platform and not to Deno, I'd like to instead focus on something a bit more generic, and that's containers. 49 | 50 | ## Running Deno in Docker 51 | 52 | Containers are magical for web applications because they allow you to define a runtime environment for your application and then just deploy that whole thing. You don't have to worry if Deno is or isn't installed on the server because it's in your container already. Let's take a look at what it takes to get a Deno container running. If you haven't used Docker or containers before, I highly recommend watching Brian Holt's ["Complete Intro To Containers" course](https://btholt.github.io/complete-intro-to-containers/intro). 53 | 54 | First, create a file in the root of the "exercise" folder called "Dockerfile". This file will be where we define how the container will be built and how the code will be executed in it. 55 | 56 | We need a base image to start from - one that has Deno in it. While Deno [doesn't yet have an "official" image](https://github.com/denoland/deno/issues/3356), most people are using an image called "hayd/docker-deno", so that's what we'll be using here. Add the following line to the top of the Dockerfile to pull in that image. 57 | 58 | ```dockerfile 59 | FROM hayd/alpine-deno 60 | ``` 61 | 62 | This image contains not only Deno, but all of the deno environment configuration that we would normally need to do to get autocompletions and the like. It also contains a default user called "deno" so that your application doesn't run as root with too many privileges. 63 | 64 | Now that we've got that image, we need to define our working directory - or rather - the directory where our application is going to go inside the container. You can call it anything you like. I usually just call it, "app". 65 | 66 | ```dockerfile 67 | FROM hayd/alpine-deno 68 | 69 | WORKDIR /app 70 | ``` 71 | 72 | We need to specify a port for the application to run on. This is important to do because when we deploy it, the hosting provider is going to be mapping this port to some random external port so the app is exposed to the internet. We'll use port 8000 here as to be doubly sure that you don't conflict with the previous exercises which you still may have running on your machine on port 3000. 73 | 74 | ```dockerfile 75 | FROM hayd/alpine-deno 76 | 77 | WORKDIR /app 78 | 79 | ENV PORT=8000 80 | ``` 81 | 82 | Now we need to copy in the application. 83 | 84 | ```dockerfile 85 | FROM hayd/alpine-deno 86 | 87 | WORKDIR /app 88 | 89 | ENV PORT=8000 90 | 91 | COPY . . 92 | ``` 93 | 94 | Next, run the application with the `CMD` command. This will be what actually executes when your Docker container is started. 95 | 96 | ```dockerfile 97 | FROM hayd/alpine-deno 98 | 99 | WORKDIR /app 100 | 101 | ENV PORT=8000 102 | 103 | COPY . . 104 | 105 | CMD ["deno", "run", "-A", "--unstable", "app.ts"] 106 | ``` 107 | 108 | Finally, expose the port 8000 so that the application can be accessed. 109 | 110 | ```dockerfile 111 | FROM hayd/alpine-deno 112 | 113 | WORKDIR /app 114 | 115 | ENV PORT=8000 116 | 117 | COPY . . 118 | 119 | CMD ["deno", "run", "-A", "--unstable", "app.ts"] 120 | 121 | EXPOSE ${PORT} 122 | ``` 123 | 124 | OK! Not too bad. Let's just recap what's happening here... 125 | 126 | 1. A default image is pulled that already has Deno installed 127 | 1. The working directory is specified 128 | 1. The PORT environment variable is specified 129 | 1. We copy our code into the container 130 | 1. We specify the command that runs our program 131 | 1. We let Docker know to expose port 8000 by exposing the value of the PORT variable 132 | 133 | Let's build the container. 134 | 135 | ### Building the container 136 | 137 | Open the VS Code Command Palette and select "Docker Images: Build Image". Select "exercise/Dockerfile". 138 | 139 | ![](../images/exercise-dockerfile.jpg) 140 | 141 | Take the default name and tag (denoexercises:latest) and press enter. The container should be built and you'll see the output in VS Code. 142 | 143 | Open the Docker Explorer in VS Code and you should see the image at the top of the "images" section... 144 | 145 | ![](../images/denoexercises-image.jpg) 146 | 147 | Right-click the "latest" image and choose "Run Interactive". 148 | 149 | Your terminal should show Deno downloading all of the dependencies in the container, checking the "app.ts" file and then a glorious... 150 | 151 | ```bash 152 | Now listening on http://0.0.0.0:8000 153 | ``` 154 | 155 | Now open your browser and see if you can access the application running on port 8000. 156 | 157 | Awesome! Now that you have a container, you can deploy it anywhere containers can run. Which is pretty much everywhere. In the next section, we'll do just that. 158 | -------------------------------------------------------------------------------- /lessons/oak/static-files.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/oak/static-files" 3 | title: "Serving Static Files" 4 | order: "7E" 5 | section: "7 - Oak web framework" 6 | description: "Burke introduces the Oak web framework for Deno" 7 | --- 8 | 9 | > Make sure you are on the [7-serving-static-files](https://github.com/burkeholland/deno-exercises/tree/7-serving-static-files) branch to follow along with this section. 10 | 11 | Serving up static files is arguably the most basic feature of a web server. For Oak, it's relatively easy to serve up static files without much ceremony. 12 | 13 | For this project, we want to have a "public" directory and everything that goes in that folder should be accessible from our templates with the "/public" path. 14 | 15 | For instance, if we were going to have a stylesheet that our "main.hbs" template references, we should be able to put it in a folder called "public/stylesheets" and then reference it like this in the "main.hbs" file... 16 | 17 | ```html 18 | 19 | ``` 20 | 21 | First, let's create a "public" folder in the exercise project root. Inside of that, create a "stylesheets" folder. In that folder, add a "style.css" and add the following CSS... 22 | 23 | ```css 24 | body { 25 | padding: 50px; 26 | font: 14px "Lucida Grande", Helvetica, Arial, sans-serif; 27 | } 28 | ``` 29 | 30 | Now reference this stylesheet from the "main.hbs" file as shown in the first code snippet in this section... 31 | 32 | ```html 33 | 34 | 35 | 36 | 37 | 38 | 39 | Oak 40 | 41 | 42 | {{{ body }}} 43 | 44 | 45 | ``` 46 | 47 | Oak contains a simple method for sending static files. It's called `send`. This method does exactly what it says - it "sends" a file from your local file system. First, we'll need to import `send` from "Oak" in our "deps.ts" file and then export it again at the bottom. 48 | 49 | ```typescript 50 | import { Application, Router, send } from "https://deno.land/x/oak/mod.ts"; 51 | import { Handlebars } from "https://deno.land/x/handlebars/mod.ts"; 52 | 53 | export { Application, Router, send, Handlebars }; 54 | ``` 55 | 56 | Now we need to create a route in the `app.ts` file to handle any requests to the "public" folder. We can write a route that goes to "/public". That will work for any file that is in the "public" directory, but the route won't trip when the route becomes "/public/stylesheets". We could create a route that is just "/public/stylesheets/:fileName". That would work. But it would only match files in the "public/stylesheets" directory. We could create multiple routes for any folder in the "public" directory. But that's going to clutter our `app.ts` with a lot of redundant routes. What we need is a wildcard route. How do we do that? 57 | 58 | What we need to do is specify a "path" parameter that can be literally anything. We can do that like this... 59 | 60 | ```typescript 61 | router.get("/public/:path", async (ctx) => {}); 62 | ``` 63 | 64 | In order to get this route to fire for _any_ path underneath the "public" folder, we have to add a special designator to the `path` parameter. This is the "+" sign. The "+" is the wildcard. It says that this "path" parameter matches EVERYTHING that comes after "public". It doesn't matter if there are more "/" or not. All of that will get sucked into the "path" parameter. 65 | 66 | ```typescript 67 | router.get("/public/:path+", async (ctx) => {}); 68 | ``` 69 | 70 | Now we call the `send` method from Oak. We'll need to pass in the context - `ctx` - and the path to the file we want. Because we're passing a `path` parameter, we can just refer to that to get the path to the file. Note that we have to give an empty string option in case this parameter is undefined. TypeScript requires this. 71 | 72 | ```typescript 73 | router.get("/public/:path+", async (ctx) => { 74 | await send(ctx, ctx.params.path || ""); 75 | }); 76 | ``` 77 | 78 | If you run this, you'll get a 404. Why? You may have noticed that Deno doesn't spit out any errors to the terminal. Let's fix that by adding an error handler so we can see what's going on here. 79 | 80 | ## Adding a global error handler 81 | 82 | The `app` object we're working with in "app.ts" has an `addEventListener` method where we can listen for a generic error event. We could then just log out the `err` object to the console... 83 | 84 | app.addEventListener("error", err => { 85 | console.log(err); 86 | }); 87 | 88 | This should show you a stack trace with an error message telling you... 89 | 90 | ``` 91 | ApplicationErrorEvent { 92 | bubbles: false, 93 | cancelable: false, 94 | composed: false, 95 | currentTarget: EventTarget { handle: [AsyncFunction], proxy: false, state: {} }, 96 | defaultPrevented: false, 97 | eventPhase: 2, 98 | target: EventTarget { handle: [AsyncFunction], proxy: false, state: {} }, 99 | timeStamp: 1605888293829, 100 | type: "error", 101 | message: "No such file or directory (os error 2)", 102 | filename: "", 103 | lineno: 0, 104 | colno: 0, 105 | error: NotFoundError: No such file or directory (os error 2) 106 | at createHttpError (httpError.ts:131:10) 107 | at send (send.ts:148:13) 108 | at async app.ts:13:5 109 | at async dispatch (middleware.ts:41:7) 110 | at async dispatch (middleware.ts:41:7) 111 | at async dispatch (middleware.ts:41:7) 112 | at async Application.#handleRequest (application.ts:252:9) 113 | } 114 | ``` 115 | 116 | The key here is "no such file or directory". This means that it can't find the file that we're looking for. Why? The reason is that we have only provided a relative path. In order for Deno to find this file, we need to pass the full path on the system. To do that, we can pass an options object as a third parameter on the `send` function. That object has a property called "root". This is where we need to specify the path of the root directory - or the directory that we're currently in. You may remember from earlier in this course that the `Deno` object has a `cwd` method which will return the current working directory. We then need to append `public` on the root since the "path" parameter won't contain this part of the path to the requested file. 117 | 118 | ```typescript 119 | router.get("/public/:path+", async (ctx) => { 120 | await send(ctx, ctx.params.path || "", { 121 | root: `${Deno.cwd()}/public`, 122 | }); 123 | }); 124 | ``` 125 | 126 | This looks kind of hacky. We're specifying the "public" string twice and we've got to handle an empty string with an `||`. There is a better way to write this. 127 | 128 | The `ctx` object contains a `request` object. On that object, you'll find a `url` object that has a `pathname` property. That `pathname` is going to contain the full path requested - which is `public/stylesheets/style.css`. Which is exactly what we want. Don't be afraid to explore these objects using the debugger to find better solutions, even though it might seem obvious to use the "path" parameter. 129 | 130 | So we can finally re-write this just so... 131 | 132 | ```typescript 133 | router.get("/public/:path+", async (ctx) => { 134 | await send(ctx, ctx.request.url.pathname, { 135 | root: Deno.cwd(), 136 | }); 137 | }); 138 | ``` 139 | 140 | Run the program again. This time, the file is served up from the "public/stylesheets" directory. Now, we can add any static assets we want, including additional JavaScript files for the frontend, images, or anything else that we'd like to send. 141 | 142 | ![styled Deno app](../images/deno-styled.jpg) 143 | 144 | **Bonus** - Instead of logging an error, return the error via a view IF and only if the application is run with the DEVELOPMENT environment variable. 145 | -------------------------------------------------------------------------------- /lessons/getting-to-know/first-program.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/getting-to-know/first-program" 3 | title: "Your first program" 4 | order: "3C" 5 | section: "3 - Getting to know Deno" 6 | description: "Burke goes over how to write your first program with Deno and execute it with the Deno CLI." 7 | --- 8 | 9 | > Switch to the [3-your-first-program](https://github.com/burkeholland/deno-exercises/tree/3-your-first-program) branch to follow along with this section. 10 | 11 | Deno programs can be written in TypeScript or JavaScript. Either will work. 12 | 13 | In the "app.ts" file in the "exercise" folder, write out "Hello World" to the terminal. 14 | 15 | ```typescript 16 | console.log("Hello World"); 17 | ``` 18 | 19 | Execute the file with Deno from your terminal. Make sure you are in the exercise directory where the "app.ts" file is located. 20 | 21 | ```bash 22 | deno run app.ts 23 | ``` 24 | 25 | You should see the following output... 26 | 27 | ```bash 28 | Check file:///home/burkeholland/dev/deno-first-look-exercises/app.ts 29 | Hello World 30 | ``` 31 | 32 | Notice that the terminal says "Check ". There is then a bit of delay before that "Hello World" shows up. 33 | 34 | Run the program a second time 35 | 36 | ```bash 37 | deno run app.ts 38 | ``` 39 | 40 | This time it doesn't say "Checking". This time it just runs and "Hello World" shows up immediately. 41 | 42 | In order to understand what's happening here, we need to understand what Deno is doing when it "Checks" a file. 43 | 44 | ## Deno run - behind the scenes 45 | 46 | While TypeScript is a first-class citizen in Deno, it still has to be JavaScript before V8 can run it. Deno has to convert the file to TypeScript using the TypeScript compiler/transpiler. When it does this, it creates a "build" of your file on your system. Let's investigate that. 47 | 48 | Navigate from your terminal to the "deno" cache directory. This will be different if you are on Windows vs Linux. You can use the "deno info" command from your terminal and it will tell you exactly where your cache folder is. 49 | 50 | Linux 51 | 52 | ``` 53 | ~/.cache/deno/gen/file/ 54 | 55 | // on my machine, it looks like this... 56 | ~/.cache/deno/gen/file/home/burkeholland/dev/deno-first-look-excercises 57 | ``` 58 | 59 | Windows 60 | 61 | ```powershell 62 | C:\Users\burkeholland\AppData\Local\deno\gen\file\ 63 | 64 | // on my machine, it looks like this... 65 | C:\Users\burkeholland\AppData\Local\deno\gen\file\C\dev\burkeholland\deno-first-look-windows 66 | ``` 67 | 68 | Inside that folder, you will find several files... 69 | 70 | - app.ts.bundleinfo 71 | - app.ts.js 72 | - app.ts.map (if this file is not present, it's because your source maps are inline in the `app.ts.js` file which is fine.) 73 | - app.ts.metadata 74 | 75 | Open this folder in VS Code by executing the following command in the terminal from the same folder where these files are located. 76 | 77 | ```bash 78 | code . 79 | ``` 80 | 81 | This is the output of your program. The "app.ts.bundleinfo" file contains your program's build info. It has paths to TypeScript definition files. 82 | 83 | If you scroll all the way down to the bottom, you'll see an embedded ".tsconfig" 84 | 85 | The "app.ts.js" file contains the JavaScript output of your code - minified and with sourcemaps. 86 | 87 | The `app.ts.meta` contains information concerning the version of your file. Deno is using these files to determine what dependencies your program has, what version it is, etc. We'll look at this again later on and you'll understand more about _why_ Deno is doing all of this. 88 | 89 | In summary, Deno is the compiler and it checks code for errors the way any strongly typed language compiler would. 90 | 91 | ## Running without checks 92 | 93 | You can go around the TypeScript checking all-together by passing the "--no-check" flag to the run command. 94 | 95 | Modify the app.ts to contain the following valid TypeScript code... 96 | 97 | ```typescript 98 | const message: string = "Hello World"; 99 | console.log(message); 100 | ``` 101 | 102 | Run it with the `--no-check` flag... 103 | 104 | ```bash 105 | deno run --no-check app.ts 106 | ``` 107 | 108 | This time the app runs without the check. There is still a slight delay as the code is transpiled, but it's faster because it's not checked for errors first. 109 | 110 | If you run the code again, it will be even faster because nothing has changed, so it doesn't need to be transpiled again. 111 | 112 | ## Executing JavaScript 113 | 114 | In the same way that you execute TypeScript, you can execute plain JavaScript. 115 | 116 | In the "app.js" file, add a line to print out "Hello World". 117 | 118 | ```javascript 119 | console.log("Hello World"); 120 | ``` 121 | 122 | Run the file from your terminal with Deno. 123 | 124 | ```bash 125 | deno run app.js 126 | ``` 127 | 128 | Notice that there is no check this time and the result is immediate. 129 | 130 | When executing JavaScript files in Node, you don't need to pass a file extension. This is why Express apps have a file called "bin/www" with no extension. 131 | 132 | Deno supports this as well. However, it will only recognize a file as TypeScript if the file has a .ts extension. In any event, the follow code works in Node and Deno... 133 | 134 | ```bash 135 | node app || deno run app 136 | Hello World 137 | ``` 138 | 139 | ## Executing remote scripts 140 | 141 | Deno can also execute scripts that are remote. That means that you literally call them with a URL. This is why the Deno docs have you call their sample "Hello World" program. This feels awfully unintuitive for a JavaScript developer. We explicitly do **not** execute scripts from other sources because we don't know what they are going to do. But since Deno is "secure by default" as we discussed earlier, the model changes and Deno actually expects you to include code from remote locations. 142 | 143 | Instead of running our local "app.ts" file, execute the remote "Hello World" example that Deno provides... 144 | 145 | ```bash 146 | deno run https://deno.land/std@0.76.0/examples/welcome.ts 147 | 148 | Download https://deno.land/std@0.76.0/examples/welcome.ts 149 | Check https://deno.land/std@0.76.0/examples/welcome.ts 150 | Welcome to Deno 🦕 151 | ``` 152 | 153 | Notice that first Deno downloads the file, then it sends it through the compiler/transpiler, then executes it. Normally, we would consider this a highly dangerous thing to do, because we don't know what this file is or what it might attempt! But because Deno will not allow any program to access your files system, the net or do virtually anything else without your permission, this is ok. 154 | 155 | But where is this file downloaded to? For that, we need to go back to the cache. 156 | 157 | ## Where Deno downloads dependencies 158 | 159 | Deno treats this file as a dependency, and downloads it to the same place it downloads all dependencies. This file isn't really a dependency that we are using in our program - it IS the program. But Deno treats it the same way it treats dependencies. 160 | 161 | Navigate from your terminal to the "deno.land" directory in the "deno" cache. This will be different if you are on Windows vs Linux... 162 | 163 | Linux 164 | 165 | ``` 166 | ~/.cache/deno/deps/https/deno.land 167 | ``` 168 | 169 | Windows 170 | 171 | ```powershell 172 | 173 | // on my machine, it looks like this... 174 | C:\Users\burkeholland\AppData\Local\deno\deps\https\deno.land 175 | ``` 176 | 177 | In that folder, provided you have never worked with Deno before, you should see files with really long names. One has no extension and another has a `.metadata.json` extension. Something like this... 178 | 179 | ```bash 180 | d85d61a352596fd18eac16f29315093cc2e293166b66528a92e171492992f148 181 | d85d61a352596fd18eac16f29315093cc2e293166b66528a92e171492992f148.metadata.json 182 | ``` 183 | 184 | You can open that first file - the one without the extension - in your editor, and you'll see the code in the "welcome.ts" file that you ran from "https://deno.land/std@0.76.0/examples/welcome.ts"... 185 | 186 | ```typescript 187 | // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. 188 | console.log("Welcome to Deno 🦕"); 189 | ``` 190 | 191 | Deno downloaded that file, cached it, transpiled it to JavaScript and executed it. 192 | -------------------------------------------------------------------------------- /lessons/what-is/typescript-first.md: -------------------------------------------------------------------------------- 1 | --- 2 | path: "/what-is/typescript-first" 3 | title: "TypeScript First" 4 | order: "2D" 5 | description: "Burke talks about why TypeScript plays an enormous role in how Deno thinks about how applications should be built." 6 | section: "2 - What is Deno" 7 | --- 8 | 9 | > Switch to the ["2-typescript-first"](https://github.com/burkeholland/deno-exercises/tree/2-typescript-first) branch to follow along with this section. 10 | 11 | Deno supports TypeScript as a first-class citizen. In fact, if you look at the [Deno project](https://github.com/denoland/deno), you'll see that it's standard library is written in TypeScript. 12 | 13 | ![](../images/stdlib-typescript.jpg) 14 | 15 | The TypeScript compiler is part of the runtime, and there is no need to transpile to JavaScript before you run a file. 16 | 17 | This may seem more like a feature than a core principal, but according to his talk, Ryan feels that dynamic languages like JavaScript and Python are very good for prototyping and scientific computing - running small batches of code to do some isolated processing. Complex systems, on the other hand, need a structured language with a type system. 18 | 19 | You may not agree with that, and that's ok. I don't know that I necessarily do myself. However, there are some key reasons to consider TypeScript as the preferred language for larger, more complex systems and applications. 20 | 21 | ## Structure and standardization 22 | 23 | One of the beautiful things about JavaScript is that there is no _right_ way to do it. Everyone organizes their projects differently. Some people use classes and some don't. Some people use objects to store collections and some people use arrays. If you remember the book - The Lorax - JavaScript is like a thneed. It is whatever you need it to be. 24 | 25 | This is also one of the drawbacks. It makes it harder for organizations to standardize on JavaScript because they have to invent their own patterns. 26 | 27 | Strongly typed object-oriented languages, by contrast, have a genuinely accepted set of patterns as laid out by books such as those laid out in the book "Design Patterns" by the notorious Gang of Four. By the way, one of those authors, Erich Gamma is the man behind VS Code. So these folks know what they are doing. 28 | 29 | ## Better Tooling 30 | 31 | One of the primary value propositions of VS Code is it's support for TypeScript. TypeScript itself is a mature and robust language, and it's object-oriented nature allows VS Code to provide signficant tooling capabilities compared to standard JavaScript. 32 | 33 | In the "exercise" project, install the Cosmos DB package from npm. We won't be doing anything with it, but it's a great example of what benefits you can get when you adopt TypeScript as your language... 34 | 35 | Make sure that you have a `package.json` file. If you do not, initialize one. 36 | 37 | ```bash 38 | npm init -y 39 | ``` 40 | 41 | Install the Azure Cosmos DB package from npm. 42 | 43 | ```bash 44 | npm i @azure/cosmos 45 | ``` 46 | 47 | Import the module and create a new instance of "CosmosClient". 48 | 49 | ```bash 50 | import cosmos from "@azure/cosmos"; 51 | 52 | const client = new cosmos.CosmosClient(""); 53 | ``` 54 | 55 | Notice that when you open the parens on "CosmosClient", VS Code suggests the parameter and parameter types. It also shows that this constructor is overloaded. That means that you can pass different numbers or types of parameters to initialize the object. One is initialized with a string, and the other is initialized as an object. 56 | 57 | ![](../images/cosmos-options.jpg) 58 | 59 | Even better, TypeScript knows what options go in that object, what their types are, and whether or not they are required. 60 | 61 | ![](../images/options-options.jpg) 62 | 63 | Selecting an option in the intellisense tells you what it's type is and the ? on the end tells you if it's required or not. 64 | 65 | These are the kinds of things that you want in an API as a developer. Plainly put, when you're writing code, it's much easier to write JavaScript. But when you're consuming someone else's code, it's much easier if it was written in TypeScript. This is why TypeScript is great for large teams working on large codebases. 66 | 67 | Note that you can get the same effect in JavaScript by including TypeScript definitions for your JavaScript. This is why you get such great tooling on a library like axios - this is the TypeScript definitions kicking in. 68 | 69 | ## Benefits of Being First-Class 70 | 71 | The benefits of TypeScript being first-class is that you don't need a transpilation step. The following code won't work in Node, because it doesn't recognize the specifics of TypeScript... 72 | 73 | ```bash 74 | const message: string = "Hello"; 75 | 76 | console.log(message); 77 | ``` 78 | 79 | > Note that Node WILL execute any file regardless of the extension. If the file contains valid JavaScript, it will work. You can try this out by putting some JavaScript in a file called index.smurf and then running it with node index.smurf 80 | 81 | In order to get TypeScript to work in Node, you have to convert it to JavaScript first. This is not hard to do in VS Code. All we need to do is initialize this project with a "tsconfig" file. 82 | 83 | From your terminal, run the following in the "exercise" folder to initialize the directory as a TypeScript project. Note that you need to have [TypeScript installed globally](https://www.typescriptlang.org/download). 84 | 85 | ```bash 86 | tsc --init 87 | ``` 88 | 89 | This creates a "tsconfig" file with a bunch of options. Like every option in the book. Most are commented out. It's not important here what these options are. We're just trying to see how TypeScript currently plays out in the real world so we can make a comparison with how it works in Deno. 90 | 91 | Now that "index.ts" file needs to be converted to JavaScript so we can run it with Node. To do that, Press Cmd/Ctrl + Shift + B in VS Code. 92 | 93 | > If no commands show up when you open the build menu, make sure that the .tsconfig file was created with the `tsc --init` command. 94 | 95 | Notice that VS Code automatically detects that this is a TypeScript project and gives you the option to do a build, or a watch. Go ahead and select Build. 96 | 97 | The TypeScript file is "transpiled" to a .js file of the same name. And this file will run in Node. But now you have a problem. Instead of having one file, now you have two. Which, no big deal right? On a small scale no, but as the project grows, you'll have a fairly cluttered project directory, especially if you are also generating source maps. Because then you have 3 files for every one code file. 98 | 99 | We often mitigate this in VS Code with the setting "files.exclude" and then using globs to hide the ".js" and ".js.map" files... 100 | 101 | ```json 102 | "files.exclude": { 103 | "**/*{.js,.js.map}": true, 104 | } 105 | ``` 106 | 107 | This has the side-effect of hiding the actual code files though. And furthermore, you need a watch process to make sure the underlying JavaScript is up to date. If you get out of date, you can spend a lot of time trying to figure out why something isn't working and it's because your watch process stopped running or some other error. 108 | 109 | When you deploy this app, the TypeScript needs to be built into JavaScript and then you don't need the TypeScript anymore and don't really want it on your production server. So what we often do is specify an output directly for the JavaScript and now we've got our project split into source and build directories. 110 | 111 | In the tsconfig file, change the "outDir" to "dist". 112 | 113 | ```json 114 | "outDir": "dist" 115 | ``` 116 | 117 | This works, except that anything that your project needs that isn't a TypeScript file ALSO needs to be copied into this dist directory. Like - say - an Express app. You'll need the templates and "public" folder from that to make sure you templates and static assets move with the project. At this point, you're probably into a build system like Gulp to try and automate this all. Simple build and copy steps can quickly balloon into tedious build setups that you would rather avoid. 118 | 119 | Now, I'm not suggesting that any of this is necessarily a bad thing. That might be the way things _should_ be but, that doesn't stop it from being a drag to set up and easy to mess up. 120 | 121 | In Deno, TypeScript is a first-class citizen. And as you'll see, when TypeScript is first-class none of this hackiness that comes from transpilation happens. Your TypeScript files ARE your code files. 122 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ## creative commons 2 | 3 | # Attribution-NonCommercial 4.0 International 4 | 5 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 6 | 7 | ### Using Creative Commons Public Licenses 8 | 9 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 10 | 11 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 12 | 13 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 14 | 15 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 16 | 17 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 18 | 19 | ### Section 1 – Definitions. 20 | 21 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 22 | 23 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 24 | 25 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 26 | 27 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 28 | 29 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 30 | 31 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 32 | 33 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 34 | 35 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 36 | 37 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 38 | 39 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 40 | 41 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 42 | 43 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 44 | 45 | ### Section 2 – Scope. 46 | 47 | a. ___License grant.___ 48 | 49 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 50 | 51 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 52 | 53 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 54 | 55 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 56 | 57 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 58 | 59 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 60 | 61 | 5. __Downstream recipients.__ 62 | 63 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 64 | 65 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 66 | 67 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 68 | 69 | b. ___Other rights.___ 70 | 71 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 72 | 73 | 2. Patent and trademark rights are not licensed under this Public License. 74 | 75 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 76 | 77 | ### Section 3 – License Conditions. 78 | 79 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 80 | 81 | a. ___Attribution.___ 82 | 83 | 1. If You Share the Licensed Material (including in modified form), You must: 84 | 85 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 86 | 87 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 88 | 89 | ii. a copyright notice; 90 | 91 | iii. a notice that refers to this Public License; 92 | 93 | iv. a notice that refers to the disclaimer of warranties; 94 | 95 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 96 | 97 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 98 | 99 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 100 | 101 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 102 | 103 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 104 | 105 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 106 | 107 | ### Section 4 – Sui Generis Database Rights. 108 | 109 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 110 | 111 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 112 | 113 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 114 | 115 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 116 | 117 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 118 | 119 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 120 | 121 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 122 | 123 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 124 | 125 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 126 | 127 | ### Section 6 – Term and Termination. 128 | 129 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 130 | 131 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 132 | 133 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 134 | 135 | 2. upon express reinstatement by the Licensor. 136 | 137 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 138 | 139 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 140 | 141 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 142 | 143 | ### Section 7 – Other Terms and Conditions. 144 | 145 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 146 | 147 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 148 | 149 | ### Section 8 – Interpretation. 150 | 151 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 152 | 153 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 154 | 155 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 156 | 157 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 158 | 159 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 160 | > 161 | > Creative Commons may be contacted at creativecommons.org --------------------------------------------------------------------------------