Categories
Deno

Deno — Workers, Libraries, and Modules

Deno is a new server-side runtime environment for running JavaScript and TypeScript apps.

In this article, we’ll take a look at how to get started with developing apps for Deno.

Workers

Deno supports the web worker API.

For example, we can write:

index.ts

const worker = new Worker(new URL("worker.js", import.meta.url).href, {
  type: "module",
  deno: true,
});
worker.postMessage({ filename: "./log.txt" });

worker.js

self.onmessage = async (e) => {
  const { filename } = e.data;
  const text = await Deno.readTextFile(filename);
  console.log(text);
  self.close();
};

log.txt

hello

Then when we run:

deno run  --unstable --allow-read index.ts

We create the worker with the Worker constructor.

We pass in the URL to the worker.

And the object specifies the type as 'module' and deno set to true so that we can run the worker.

worker.js has the worker.

self is the worker instance. The onmessage method accepts message passed in by calling postMessage .

And then we call Deno.readTextFile method to read a file in the worker.

We then should see hello logged in the console.

Reloading Modules

Deno caches modules by default without fetching or recompiling it.

If we need to reload them, we run:

deno cache --reload index.ts

to reload everything used by index.ts .

We can also reload a specific module used by index.ts by running:

deno cache --reload=https://deno.land/std@0.75.0 index.ts

If we want to reload multiple modules used by index.ts , we run:

deno cache --reload=https://deno.land/std@0.75.0/fs/copy.ts,https://deno.land/std@0.75.0/fmt/colors.ts index.ts

Lock Files

Deno stores and check the subresource integrity for modules using a small JSON file.

The -lock=lock.json flag enables and specifies lock file checking.

To update the lock file, we run:

--lock=lock.json --lock-write

We can use the  — -lock=lock.json option to check the data when we run our app.

Standard Library

We should run pinned versions of imports to avoid unintended changes.

For example, instead of writing:

import { copy } from "https://deno.land/std/fs/copy.ts";

We should include the version number with the import by writing:

import { copy } from "https://deno.land/std@0.75.0/fs/copy.ts";

We may use libraries that have unstable Deno APIs.

The copy module we have above is unstable, so to use it, we run:

deno run --allow-read --allow-write --unstable main.ts

to enable unstable APIs.

Import and Export Modules

We can use standard ES modules to with Deno apps.

For example, we can write:

math.ts

export const add = (a: number, b: number) => a + b;
export const multiply = (a: number, b: number) => a * b;

index.ts

import { add, multiply } from "./math.ts";

console.log(add(1, 2))
console.log(multiply(1, 2))

We have math.ts that exports the add and multiply functions.

Then we use them in index.ts .

Remote Import

We can also import modules directly from a remote URL.

For example, we can write:

import {
  add,
  multiply,
} from "https://x.nest.land/ramda@0.27.0/source/index.js";

console.log(add(1, 2))
console.log(multiply(1, 2))

We import the add and multiple functions from https://x.nest.land/ramda@0.27.0/source/index.js .

Then we can use them the same way.

Conclusion

We can use web workers directly with Deno.

Also, we can import modules from various sources.

Categories
Deno

Deno — Command-Line and Permissions

Deno is a new server-side runtime environment for running JavaScript and TypeScript apps.

In this article, we’ll take a look at how to get started with developing apps for Deno.

Command-Line Interface

We can get help by running:

deno help

or:

deno -h

for short.

We can also write:

deno --help

to do the same thing.

Script Arguments

We can get command-line arguments in our script with the Deno.args property.

For example, we can write:

index.ts

console.log(Deno.args);

Then when we run:

deno run index.ts a b -c --quiet

We get:

[ "a", "b", "-c", "--quiet" ]

from the console output.

Permissions

Permission is required for running code that requires access to various resources.

They have to enabled specifically by default.

The following permissions available:

  • -A, — allow-all — Allow all permissions. This disables all security.
  •  — allow-env — Allow environment access for things like getting and setting of environment variables.
  •  — allow-hrtime — Allow high-resolution time measurement. High-resolution time can be used in timing attacks and fingerprinting.
  •  — allow-net=<url> — Allow network access. We can specify an optional, comma-separated list of domains to provide an allow-list of allowed domains.
  •  — allow-plugin — Allow loading plugins. Please note that — allow-plugin is an unstable feature.
  •  — allow-read=<allow-read> — Allow file system read access. We can specify an optional, comma-separated list of directories or files to provide an allow-list of allowed file system access.
  •  — allow-run — Allow running subprocesses. Be aware that subprocesses are not run in a sandbox and therefore do not have the same security restrictions as the Deno process. Therefore, use with caution.
  •  — allow-write=<allow-write> — Allow file system write access. You can specify an optional, comma-separated list of directories or files to provide an allow-list of allowed file system access.

For example, if we have a program that makes HTTP requests like:

const [url] = Deno.args;
const res = await fetch(url);
const body = new Uint8Array(await res.arrayBuffer());
await Deno.stdout.write(body);

We run it with:

deno run --allow-net index.ts https://yesno.wtf/api

to let the program access the Internet.

Permission APIs

We can query form permissions by using the Deno.permissions.query method with an object that has the permissions we want to query.

For example, we can write:

index.ts

const desc1 = { name: "read", path: "/foo" } as const;
console.log(await Deno.permissions.query(desc1));

const desc2 = { name: "read", path: "/foo/bar" } as const;
console.log(await Deno.permissions.query(desc2));

const desc3 = { name: "read", path: "/bar" } as const;
console.log(await Deno.permissions.query(desc3));

Then when we run:

deno run --unstable index.ts

We see:

PermissionStatus { state: "prompt" }
PermissionStatus { state: "prompt" }
PermissionStatus { state: "prompt" }

logged in the console.

We need the --unstable option to make the Deno.permissions.query method available.

We can revoke permissions by using the Deno.permissions.revoke method:

const desc = { name: "read", path: "/foo/bar" } as const;
console.log(await Deno.permissions.revoke(desc));

const strongDesc = { name: "read", path: "/foo" } as const;
await Deno.permissions.revoke(strongDesc);

Then we get:

PermissionStatus { state: "prompt" }

displayed.

Conclusion

We can get and set permissions with Deno.

Categories
Deno

Getting Started with Writing Server-Side Apps for the Deno Runtime Environment

Deno is a new server-side runtime environment for running JavaScript and TypeScript apps.

In this article, we’ll take a look at how to get started with developing apps for Deno.

Installation

Deno ships as a single executable with no dependencies.

So we can install them easily.

It’s available on multiple platforms.

We can run the following commands to install them:

Shell (Mac, Linux):

$ curl -fsSL https://deno.land/x/install/install.sh | sh

PowerShell (Windows):

$ iwr https://deno.land/x/install/install.ps1 -useb | iex

Homebrew (Mac):

$ brew install deno

Chocolatey (Windows):

$ choco install deno

Scoop (Windows):

$ scoop install deno

Build and install from source using Cargo

$ cargo install deno

Getting Started

To create a hello world app, we can write:

console.log("hello world");

console is available within the Deno runtime.

We can create a simple server app by writing:

import { serve } from "https://deno.land/std@0.75.0/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");
for await (const req of s) {
  req.respond({ body: "Hello Worldn" });
}

We import the server module directly from the URL.

Then we call serve to create our server.

And we listen for requests by looping through the s array and send our response with req.respond .

Now we should see ‘Hello world’ on the browser screen.

Making an HTTP Request

We can make an HTTP request by writing:

index.ts

const [url] = Deno.args;
const res = await fetch(url);
const body = new Uint8Array(await res.arrayBuffer());
await Deno.stdout.write(body);

Then we go into our project and run it by running:

deno run --allow-net index.ts https://yesno.wtf/api

The --allow-net option is required to access networks.

Deno.args lets us get the command line arguments.

fetch lets us make the HTTP request with the given url .

And we get the request by call res.arrayBuffer to parse the body.

And then we write the response to the screen with Deno.stdout.write .

Reading a File

Deno comes with methods to read a file right out of the box.

To do this, we write:

index.ts

const filenames = Deno.args;
for (const filename of filenames) {
  const file = await Deno.open(filename);
  await Deno.copy(file, Deno.stdout);
  file.close();
}

We get the file paths from Deno.args .

Then we loop through the filenames and call Deno.open to open the files.

Then we call Deno.copy to copy the file content to stdout to display them on the screen.

When we’re done, we call file.close to close the filehandle.

Now when we run;

deno run --allow-read index.ts files/bar.txt files/foo.txt

And assuming files/bar.txt and files/foo.txt exist, then we should see the content of each file displayed.

The --allow-read flag lets us enable permission to read files from the file system.

Conclusion

We can create simple server-side JavaScript or TypeScript apps and run them with the Deno runtime.

Categories
Vuetify

Vuetify — Badges and Banners

Vuetify is a popular UI framework for Vue apps.

In this article, we’ll look at how to work with the Vuetify framework.

Badges

The v-badge component lets us add an avatar-like icon or text onto the component to highlight information to the user.

They appear as superscripts or subscripts.

For example, we can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-toolbar>
          <v-tabs dark background-color="primary" grow>
            <v-tab>
              <v-badge color="pink" dot>One</v-badge>
            </v-tab> <v-tab>
              <v-badge color="green" content="6">Two</v-badge>
            </v-tab> <v-tab>
              <v-badge color="deep-purple accent-4" icon="mdi-vuetify">Three</v-badge>
            </v-tab>
          </v-tabs>
        </v-toolbar>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    alert: false,
  }),
};
</script>

We add badges to tab links with the v-tab component.

The color can be changed with the color prop.

icon lets us change the icon.

Show Badge on Hover

We can make a badge shows on hover with the v-hover component.

For example, we can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-badge
          :value="hover"
          color="deep-purple accent-4"
          content="1000"
          left
          transition="slide-x-transition"
        >
          <v-hover v-model="hover">
            <v-icon color="grey lighten-1" large>mdi-account-circle</v-icon>
          </v-hover>
        </v-badge>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    hover: undefined,
  }),
};
</script>

to add a badge that shows on hover.

The hover state is controlled by the hover state.

v-model son the v-hover component sets the hover state.

Dynamic Notifications

We can create dynamic notifications with badges.

The content can be controlled with the content prop.

For example, we can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <div>
          <v-btn class="mx-1" color="primary" @click="messages++">Send Message</v-btn> <v-btn class="mx-1" color="error" @click="messages = 0">Clear Notifications</v-btn>
        </div> <v-badge :content="messages" :value="messages" color="green" overlap>
          <v-icon large>mdi-email</v-icon>
        </v-badge>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    messages: 0,
  }),
};
</script>

We have the Send Message button that increments the message state.

This causes the content to update with the latest message value.

Banners

The v-banner component is used as a message for users with 1 to 2 actions.

It can have a single line or multiple lines.

For example, we can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-banner single-line :sticky="sticky">
          Hello world.
          <template v-slot:actions>
            <v-btn text color="deep-purple accent-4">Get Online</v-btn>
          </template>
        </v-banner>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    sticky: true
  }),
};
</script>

We have the v-banner component with the single-line prop to display a single line banner.

The sticky controls whether the banner is sticky or not.

Two-Line Banner

We can add a 2 line banner to store more data.

For example, we can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-banner>
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus nec sem id malesuada.
          Curabitur lacinia sem et turpis euismod, eget elementum ex pretium.
          <template
            v-slot:actions
          >
            <v-btn text color="primary">Dismiss</v-btn>
            <v-btn text color="primary">Retry</v-btn>
          </template>
        </v-banner>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({}),
};
</script>

to add a longer message.

The actions slot has the action buttons.

Conclusion

We can add badges and banners to our app with Vuetify.

Categories
Vuetify

Vuetify — Alert, Containers, and Avatars

Vuetify is a popular UI framework for Vue apps.

In this article, we’ll look at how to work with the Vuetify framework.

Alert Transition

Transition effects can be applied when we add alerts.

For instance, we can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <div class="text-center mb-4">
          <v-btn color="primary" @click="alert = !alert">Toggle</v-btn>
        </div>
        <v-alert
          :value="alert"
          color="pink"
          dark
          border="top"
          icon="mdi-home"
          transition="scale-transition"
        >
          lorem ipsum
        </v-alert>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    alert: false
  }),
};
</script>

to add our alert with the transition.

We just add the transition prop to add the effect.

Application

The v-app component is a container for components like v-navigator-drawer , v-app-bar , v-footer , and other components.

It helps create our app with proper sizing around the v-main component.

This lets us avoid the hassle of managing layout sizing.

v-app is required for all apps.

It ensures that the proper styles are applied to the whole app.

Also, it should only be included once.

For example, we can write:

<template>
  <v-app>
    <v-app-bar
      app
      color="primary"
      dark
    >
      <div class="d-flex align-center">
        <v-img
          alt="Vuetify Logo"
          class="shrink mr-2"
          contain
          src="https://cdn.vuetifyjs.com/images/logos/vuetify-logo-dark.png"
          transition="scale-transition"
          width="40"
        /><v-img
          alt="Vuetify Name"
          class="shrink mt-1 hidden-sm-and-down"
          contain
          min-width="100"
          src="https://cdn.vuetifyjs.com/images/logos/vuetify-name-dark.png"
          width="100"
        />
      </div> <v-spacer></v-spacer> <v-btn
        href="https://github.com/vuetifyjs/vuetify/releases/latest"
        target="_blank"
        text
      >
        <span class="mr-2">Latest Release</span>
        <v-icon>mdi-open-in-new</v-icon>
      </v-btn>
    </v-app-bar> <v-main>
      <HelloWorld/>
    </v-main>
  </v-app>
</template><script>
import HelloWorld from './components/HelloWorld';export default {
  name: 'App', components: {
    HelloWorld,
  }, data: () => ({
    //
  }),
};
</script>

to use it.

v-app wraps around the whole app.

And we can have all the other Vuetify components inside.

Aspect Ratios

We can use the v-responsive component to add a container with a specific aspect ratio.

For example, we can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-responsive :aspect-ratio="16/9">
          <v-card-text>Lorem ipsum</v-card-text>
        </v-responsive>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    alert: false,
  }),
};
</script>

We added a 16×9 container with the v-response component and the aspect-ratio prop.

Avatars

The v-avatar component lets us display circular user profile pictures.

For example, we can add one by writing:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-avatar color="green" size="36">
          <span class="white--text headline">36</span>
        </v-avatar>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    alert: false,
  }),
};
</script>

We added a green avatar with the color prop.

size is in pixels.

Also, we can make it square with a tile prop:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-avatar tile color="blue">
          <v-icon dark>mdi-alarm</v-icon>
        </v-avatar>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    alert: false,
  }),
};
</script>

The default slot of v-avatar accepts the v-icon component, image or text.

We can write:

<template>
  <v-container>
    <v-row class="text-center">
      <v-col col="12">
        <v-avatar color="blue">
          <v-avatar>
            <img src="https://cdn.vuetifyjs.com/images/john.jpg" alt="John" />
          </v-avatar>
        </v-avatar>
      </v-col>
    </v-row>
  </v-container>
</template><script>
export default {
  name: "HelloWorld",
  data: () => ({
    alert: false,
  }),
};
</script>

to add an image.

Conclusion

We can add alerts, avatars, and responsive containers with Vuetify.