iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
💖

Getting Started with Deno Casually!

に公開

You can start using Deno from the smallest tasks!

  • Deno x Jupyter is highly recommended as a playground.
  • You can easily turn your scripts into CLI tools.

I'll give a brief introduction to these points.

Installing Deno

Refer to the site below to install it. There are various methods available!

https://docs.deno.com/runtime/getting_started/installation/

The version at the time of writing is as follows:

> deno --version
deno 2.1.4 (stable, release, aarch64-apple-darwin)
v8 13.0.245.12-rusty
typescript 5.6.2

Running Deno in Jupyter Notebook

What is Jupyter Notebook?

Simply put, it's a tool that allows you to execute code in units of cells and check the results.
It is commonly seen in Python machine learning applications, such as Google Colab.

You might think it only runs Python, but Deno can actually run in it too!
(I'll explain the basic usage later.)

Setup

Install Jupyter

Since the jupyter command is required, refer to the following site to install it.

https://jupyter.org/install

The version at the time of writing is as follows:

> jupyter --version
Selected Jupyter core packages...
IPython          : 8.31.0
ipykernel        : 6.29.5
ipywidgets       : not installed
jupyter_client   : 8.6.3
jupyter_core     : 5.7.2
jupyter_server   : 2.15.0
jupyterlab       : 4.3.4
nbclient         : 0.10.2
nbconvert        : 7.16.4
nbformat         : 5.10.4
notebook         : 7.3.2
qtconsole        : not installed
traitlets        : 5.14.3

Install Deno kernel

Install the kernel to run Deno in Jupyter.
You can install it by running the following command:

deno jupyter --unstable --install

https://docs.deno.com/runtime/reference/cli/jupyter/

Install the Jupyter extension for VS Code

Since we will be using VS Code for development, install the following extension.
Now the setup is complete!

https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter

Playing with Deno x Jupyter

Creating a file

When you create and open a *.ipynb file in VS Code, the following screen will appear.
You can change the kernel using the icon in the top right.

Clicking it will display a list of kernels; select "Deno".

If it doesn't appear,
select "Select Another Kernel..." -> "Jupyter Kernel..." -> "Deno" in that order.

A brief introduction to usage

You can write code in cells and execute them on a per-cell basis.

You can write multiple lines of code in a single cell, and the value of the last line is automatically displayed. You can also refer to values defined in previous cells.

It is possible to end up in a state where the results look different from what they would be if the program were executed sequentially from the top—for example, if you run a cell below and then edit and rerun an upper cell.

In such cases, use the buttons to "Run All," "Run All Above Selected Cell," or "Run All Below Selected Cell" as needed!

Playing with packages

Since Deno can import packages in URL format, you can easily try them out on Jupyter without needing to set up a new project!
Since you can also use npm packages with npm:{package_name}(@{version}), let's try calling the OpenAI API using openai!

*Note: The content of the program itself is not the main focus, but to run the following code, you will need to issue an API key on the OpenAI developer platform.

import OpenAI from "npm:openai@4.77.0"
const client = new OpenAI({
  // You need to set environment variables beforehand, e.g., via `export MY_OPENAI_API_KEY={your_key}`
  apiKey: Deno.env.get("MY_OPENAI_API_KEY"),
})
const chatRes = await client.chat.completions.create({
  model: "gpt-4o-mini",
  messages: [
    { role: "system", content: "You are a helpful assistant." },
    { role: "user", content: "Hello!" },
  ],
})

After running the code above, you might be curious about what value is stored in chatRes. Let's enter just chatRes in a cell and run it.

Since the desired value is in chatRes.choices[0].message.content, let's enter that in the next cell and run it.

We got the value we wanted!
Now, let's turn this into a function so we can send any text to the chat.

const myChat = async (text: string): string => {
  const client = new OpenAI({
    apiKey: Deno.env.get("MY_OPENAI_API_KEY"),
  })

  const chatRes = await client.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: text },
    ],
  })

  return chatRes.choices[0].message.content
}

Let's try running the myChat function.

It works exactly as expected!

As shown, this is a great environment to use as a playground where you can easily import and execute any package!
Since cell execution results are saved in the file, you can keep them as notes and look back at them later!

Also, while we only dealt with string output this time, you can also display HTML, Markdown, and images on Jupyter Notebook.

Turning scripts into CLI tools

Calling Deno with a Shebang

A "Shebang" is a notation like #!/bin/sh found at the first line of a shell script. By using #!/usr/bin/env -S deno run, you can call Deno from a shell script!

https://docs.deno.com/examples/hashbang_tutorial/

Create a file named test.ts and add the following content:

test.ts
#!/usr/bin/env -S deno run -A
console.log(Deno.args[0])

Grant execution permissions and try running it.

> chmod u+x test.ts
> ./test.ts Hello!
Hello!

Deno has been executed!

Creating the mychat command

Now, let's turn the myChat function into a CLI tool!
Next, create a file named mychat without an extension.

mychat
#!/usr/bin/env -S deno run -A --ext=ts
import OpenAI from "npm:openai@4.77.0"
const myChat = async (text: string): string => {/** omitted */}

console.log(await myChat(Deno.args[0]))

I've added --ext=ts after deno run -A. This is an option to have the file treated as TypeScript even without an extension.

Just like before, grant execution permissions and try running it.

> chmod u+x mychat
> ./mychat Hello!
Hello! How can I help you today?

> ./mychat Please briefly explain Deno.
Deno is a modern JavaScript and TypeScript runtime developed by Ryan Dahl, the creator of Node.js. Deno has the following features:

1. **Security**: Deno is secure by default, requiring explicit permission to access the file system or network.
2. **TypeScript Support**: TypeScript is supported natively and can be executed directly without compilation.
3. **Simple Module Management**: Modules can be imported directly from URLs, eliminating the need for a package manager like npm.
4. **Standard Library**: Deno includes a rich standard library that complies with web standards.

Deno aims to provide developers with a modern and secure development experience.

It worked as expected!
If you add the path to mychat to your environment's PATH, it becomes a CLI tool you can call from anywhere!

Summary

  • Deno x Jupyter is highly recommended as a playground.
  • You can easily turn your scripts into CLI tools.

This was an introductory article about these features.
Thank you for reading until the end.

Discussion