Skip to content
This repository was archived by the owner on May 17, 2024. It is now read-only.
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion data/benchmarking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @run deno bench <url>
* @resource {https://docs.deno.com/runtime/manual/tools/benchmarker} Manual: Benchmarker tool
* @resource {/http-requests} Example: HTTP Requests
*
*
* When writing libraries, a very common task that needs to be done is
* testing the speed of methods, usually against other libraries. Deno
* provides an easy-to-use subcommand for this purpose.
Expand Down
17 changes: 9 additions & 8 deletions data/byte-manipulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,32 @@
* @difficulty beginner
* @tags cli
* @run <url>
* @resource {$std/bytes} Doc: std/bytes
* @resource {https://jsr.io/@std/bytes} Doc: @std/bytes
* @dependency jsr:@std/bytes
*
* When working with lower-level data we often deal
* with byte arrays in the form of Uint8Arrays. There
* are some common manipulations and queries that can
* be done and are included with the standard library.
*/

// Let's initialize some byte arrays
import { concat } from "@std/bytes/concat";
import { repeat } from "@std/bytes/repeat";
import { copy } from "@std/bytes/copy";

const a = new Uint8Array([0, 1, 2, 3, 4]);
const b = new Uint8Array([5, 6, 7, 8, 9]);
const c = new Uint8Array([4, 5]);

// We can concatenate two byte arrays using the
// concat method
import { concat } from "$std/bytes/concat.ts";
// concat method.
const d = concat([a, b]);
console.log(d); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

// Sometimes we need to repeat certain bytes
import { repeat } from "$std/bytes/repeat.ts";
// Repeat can be used to repeat a chunk of bytes a specified number of times.
console.log(repeat(c, 4)); // [4, 5, 4, 5, 4, 5, 4, 5]

// Sometimes we need to mutate a Uint8Array and need a copy
import { copy } from "$std/bytes/copy.ts";
// We can also copy a chunk of bytes from one array to another.
const cpy = new Uint8Array(5);
console.log("Bytes copied:", copy(b, cpy)); // 5
console.log("Bytes:", cpy); // [5, 6, 7, 8, 9]
33 changes: 16 additions & 17 deletions data/checking-file-existence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@
* @tags cli, deploy
* @run --allow-read --allow-write <url>
*
* Sometimes we as developers think that we need to check
* if a file exists or not. More often than not, we are
* entirely wrong.
* Often one reaches to checking if a file exists before performing an operation
* on it. This is a common anti-pattern that can lead to race conditions. This
* example demonstrates how to avoid this anti-pattern.
*/

// Let's say we wanted to create a folder if one doesn't
// already exist. Logically it makes sense to first verify
// that the folder exists, then try to create it right?
// Wrong. This will create a race condition where if a folder
// gets created in between when you check if the folder exists
// and when you create a folder, your program will crash.
// Instead, you should just create a folder and try to catch
// errors like so.
// You may want to create a folder if it does not exist. The naive way to do
// this is to check if the folder exists and then create it if it does not.
// This is an anti-pattern as it can lead to no folder being created if the
// folder is deleted between the check and the creation.
//
// Instead of checking for existence, you should simply try to create the
// folder and catch the error if it already exists.
try {
await Deno.mkdir("new_dir");
} catch (err) {
Expand All @@ -25,17 +24,17 @@ try {
}
}

// This applies to almost every usecase. If you have a niche
// usecase that requires you to check for existence of a file
// without doing an filesystem operations other than that
// (which is quite rare), then you can simply lstat the file
// and catch the error.
// In some cases, you may still have to check if a file exists or not. For
// example you may want to avoid expensive work to compute the content of a file
// to be created, if the file already exists.
// In this case, you can call `Deno.lstat` to check if the file exists, and
// catch the `NotFound` error if it does not.
try {
await Deno.lstat("example.txt");
console.log("exists!");
} catch (err) {
if (!(err instanceof Deno.errors.NotFound)) {
throw err;
}
console.log("not exists!");
console.log("does not exists!");
}
5 changes: 3 additions & 2 deletions data/command-line-arguments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
* @tags cli
* @run <url> Deno Sushi --help --version=1.0.0 --no-color
* @resource {https://deno.land/api?s=Deno.args} Doc: Deno.args
* @resource {$std/cli/parse_args.ts} Doc: std/cli
* @resource {https://jsr.io/@std/cli} Doc: std/cli
* @dependency jsr:@std/cli
*
* Command line arguments are often used to pass configuration options to a
* program.
Expand All @@ -17,7 +18,7 @@ console.log(`Hello ${name}, I like ${food}!`);

// Often you want to parse command line arguments like `--foo=bar` into
// structured data. This can be done using `std/cli`.
import { parseArgs } from "$std/cli/parse_args.ts";
import { parseArgs } from "@std/cli/parse_args";

// The `parseArgs` function takes the argument list, and a list of options. In these
// options you specify the types of the accepted arguments and possibly default
Expand Down
32 changes: 19 additions & 13 deletions data/dependency-management.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,29 @@
* @resource {/import-export} Example: Importing & Exporting
* @run <url>
*
* It is unwieldy to have to import the same remote module over and over again.
* Deno provides some conventions to make managing dependencies easier.
* It is unwieldy to have to specify version constraints for the same module
* over and over again in your code. Deno provides tools to make managing
* dependencies easier.
*/

// File: ./deps.ts

// The Deno ecosystem has a convention to re-export all remote dependencies from
// a deps.ts file at the root of the repo. This keeps remote dependencies
// organized, and in a single place.
export * as http from "$std/http/mod.ts";
export * as path from "$std/path/mod.ts";
/* File: ./deno.json
// The `deno.json` file acts like an import map, allowing you to specify
// aliases for remote modules.
{
"imports": {
"@std/path": "jsr:@std/path@^0.220",
"@std/bytes": "jsr:@std/bytes@^0.220"
}
}
*/

// File: ./main.ts

// Other files can then import dependencies from the deps.ts file.
// Other files can import modules using the aliases specified in `deno.json`.
// deno-lint-ignore no-unused-vars
import * as path from "@std/path";
// deno-lint-ignore no-unused-vars
import { path } from "./deps.ts";
import { concat } from "@std/bytes/concat";

// Doing this makes package version upgrades really easy, as all external
// dependency specifiers live in the same file.
// Doing this makes package version upgrades really easy, as the version
// constraints for all dependencies are in one place.
36 changes: 16 additions & 20 deletions data/hex-base64-encoding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,38 +3,34 @@
* @difficulty beginner
* @tags cli
* @run <url>
* @resource {https://jsr.io/@std/encoding} Doc: @std/encoding
* @dependency jsr:@std/encoding
*
* There are a few cases where it would be practical to encode
* and decode between different string and array buffer formats.
* The Deno standard library makes this easy.
*/

// The standard library provides hex and base64 encoding and decoding utilities
import * as base64 from "$std/encoding/base64.ts";
import * as hex from "$std/encoding/hex.ts";
import { decodeBase64, encodeBase64 } from "@std/encoding/base64";
import { decodeHex, encodeHex } from "@std/encoding/hex";

// We can easily encode a string or an array buffer into base64 using the base64.encode method.
const base64Encoded = base64.encode("somestringtoencode");
console.log(base64.encode(new Uint8Array([1, 32, 67, 120, 19])));
// We can easily encode a string into base64 using the encodeBase64 method.
const base64Encoded = encodeBase64("somestringtoencode");
console.log(base64Encoded); // "c29tZXN0cmluZ3RvZW5jb2Rl"

// We can then decode base64 into a byte array using the decode method.
const base64Decoded = base64.decode(base64Encoded);
// We can then decode base64 into a byte array using the decodeBase64 method.
const base64Decoded = decodeBase64(base64Encoded);
console.log(base64Decoded); // Uint8Array(18) [ 115, 111, 109, 101, 115, ... ]

// If we want to get the value as a string we can use the built-in TextDecoder.
// We will use these a lot so we can store them in variables to reuse them.
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
console.log(textDecoder.decode(base64Decoded));
console.log(textDecoder.decode(base64Decoded)); // "somestringtoencode"

// To encode hex, we always use array buffers.
// To use a string as an input we can encode our text.
const arrayBuffer = textEncoder.encode("somestringtoencode");
const hexEncoded = hex.encode(arrayBuffer);
console.log(hexEncoded);

// To read our hex values as a string, we can decode the buffer.
console.log(textDecoder.decode(hexEncoded));
// We can also encode a string into hex using the encodeHex method.
const hexEncoded = encodeHex("some text to encode");
console.log(hexEncoded); // "736f6d65207465787420746f20656e636f6465"

// We can convert back to a string by using the decode method.
const hexDecoded = hex.decode(hexEncoded);
console.log(textDecoder.decode(hexDecoded));
const hexDecoded = decodeHex(hexEncoded);
console.log(textDecoder.decode(hexDecoded)); // "some text to encode"
5 changes: 3 additions & 2 deletions data/http-server-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
* @tags cli, deploy
* @run --allow-net --allow-read <url>
* @resource {https://deno.land/api?s=Deno.serve} Doc: Deno.serve
* @resource {$std/http/file_server.ts} Doc: std/http/file_server
* @resource {https://jsr.io/@std/http/doc/file_server/~} Doc: @std/http/file_server
* @resource {/http-server} Example: HTTP Server: Hello World
* @dependency jsr:@std/http
*
* An example of a HTTP server that serves files.
*/

// Import utility methods for serving files with mime types.
import { serveDir, serveFile } from "$std/http/file_server.ts";
import { serveDir, serveFile } from "@std/http/file_server";

// Here we start a simple server
Deno.serve((req: Request) => {
Expand Down
7 changes: 5 additions & 2 deletions data/import-export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,10 @@ sayHello("World");
import * as util from "./util.ts";
util.sayHello("World");

// Imports don't have to be relative, they can also reference absolute file or
// https URLs.
// Imports don't have to be relative, they can also reference absolute files,
// https URLs, or JSR packages.
import { VERSION } from "https://deno.land/std/version.ts";
console.log(VERSION);

// deno-lint-ignore no-unused-vars
import { parse } from "jsr:@std/yaml";
2 changes: 1 addition & 1 deletion data/importing-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
// File: ./main.ts

// JSON files can be imported in JS and TS modules. When doing so, you need to
// specify the "json" import assertion type.
// specify the type: "json" import attribute.
import file from "./version.json" with { type: "json" };
console.log(file.version);

Expand Down
7 changes: 4 additions & 3 deletions data/mongo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@
* @difficulty intermediate
* @tags cli, deploy
* @run --allow-net --allow-sys --allow-read <url>
* @resource {https://deno.land/x/mongo} Deno MongoDB on deno.land/x
* @resource {https://www.npmjs.com/package/mongodb} MongoDB on npmjs.com
* @dependency npm:mongodb
*
* Using the Deno MongoDB client, you can connect to a Mongo database
* Using the official MongoDB client, you can connect to a Mongo database
* running anywhere.
*/

import { MongoClient } from "npm:mongodb@6.1.0";
import { MongoClient } from "mongodb";

// Create a new instance of the MongoDB client running locally on port 27017
const client = new MongoClient("mongodb://127.0.0.1:27017");
Expand Down
19 changes: 11 additions & 8 deletions data/npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,27 @@
* @run --allow-net --allow-read --allow-env <url>
* @resource {https://docs.deno.com/runtime/manual/node} Node.js / npm support in Deno
* @resource {https://docs.deno.com/runtime/manual/node/npm_specifiers} npm: specifiers
* @resource {https://www.npmjs.com/package/express} express module on npm
* @resource {https://www.npmjs.com/package/express} express on npmjs.com
* @dependency npm:express
* @dependency npm:@types/express
*
* Use JavaScript modules from npm in your Deno programs with the "npm:"
* specifier in your imports.
*/

// Import the express module from npm using an npm: prefix, and appending a
// version number. Dependencies from npm can be configured in an import map
// also.
import express from "npm:express@4.18.2";
// After adding the module using deno add, you can import it like any other
// module.

// Create an express server
// @deno-types="@types/express";
import express from "express";

// Create an express server.
const app = express();

// Configure a route that will process HTTP GET requests
// Configure a route that will process HTTP GET requests.
app.get("/", (_req, res) => {
res.send("Welcome to the Dinosaur API!");
});

// Start an HTTP server using the configured Express app
// Start an HTTP server using the configured Express app.
app.listen(3000);
4 changes: 3 additions & 1 deletion data/parsing-serializing-csv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
* @run <url>
* @resource {/import-export} Example: Importing & Exporting
* @resource {https://datatracker.ietf.org/doc/html/rfc4180} Spec: CSV
* @resource {https://jsr.io/@std/csv} Doc: @std/csv
* @dependency jsr:@std/csv
*
* CSV is a data serialization format that is designed to be portable for table-like applications.
*/
import { parse, stringify } from "$std/csv/mod.ts";
import { parse, stringify } from "@std/csv";

// To parse a CSV string, you can use the the standard library's CSV
// parse function. The value is returned as a JavaScript object.
Expand Down
4 changes: 3 additions & 1 deletion data/parsing-serializing-toml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
* @run <url>
* @resource {/import-export} Example: Importing & Exporting
* @resource {https://toml.io} Spec: TOML
* @resource {https://jsr.io/@std/toml} Doc: @std/toml
* @dependency jsr:@std/toml
*
* TOML is a widely used configuration language designed to be feature-rich and intuitive to write.
*/
import { parse, stringify } from "$std/toml/mod.ts";
import { parse, stringify } from "@std/toml";

// To parse a TOML string, you can use the the standard library's TOML
// parse function. The value is returned as a JavaScript object.
Expand Down
4 changes: 3 additions & 1 deletion data/parsing-serializing-yaml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
* @run <url>
* @resource {/import-export} Example: Importing & Exporting
* @resource {https://yaml.org} Spec: YAML
* @resource {https://jsr.io/@std/yaml} Doc: @std/yaml
* @dependency jsr:@std/yaml
*
* YAML is a widely used data serialization language designed to be easily human readable and writeable.
*/
import { parse, stringify } from "$std/yaml/mod.ts";
import { parse, stringify } from "@std/yaml";

// To parse a YAML string, you can use the the standard library's YAML
// parse function. The value is returned as a JavaScript object.
Expand Down
5 changes: 3 additions & 2 deletions data/path-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@
* @difficulty beginner
* @tags cli
* @run --allow-read <url>
* @resource {$std/path} Deno: std/path
* @resource {https://jsr.io/@std/path} Doc: @std/path
* @resource {https://deno.land/api?s=Deno.cwd} Deno: Deno.cwd
* @dependency jsr:@std/path
*
* Many applications need to manipulate file paths in one way or another.
* The Deno standard library provides simple utilities for this.
*/

// First we will import the module from the Deno standard library
import * as path from "$std/path/mod.ts";
import * as path from "@std/path";

// Converting from a file url to a directory can be done simply by the `fromFileUrl`
// method from the appropriate implementation.
Expand Down
Loading