Making a Deno 2 app in 15 minutes

Deno is an open-source JavaScript runtime, and its version 2 was recently announced. This article demonstrates how to set up, develop, and build a simple Deno app.


Setup

1) The setup is just 1 step.

# Mac / Linux
curl -fsSL https://deno.land/install.sh | sh

# Windows
irm https://deno.land/install.ps1 | iex

2) Restart your terminal to load Deno.

3) Check if Deno is loaded by running this command.

deno --help

Develop

1) Our goal is to create a command line application. It should ask the user to enter a prompt and get OpenAI GPT to react based on the prompt.

2) Start by creating a new script file, for example, main.ts

3) First, we create a function that accepts a string input.

function fetchCompletion(prompt: string) {
}

4) Then, we send the input to the OpenAI completion endpoint.

function fetchCompletion(prompt: string) {
  return fetch("https://api.openai.com/v1/chat/completions", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${"sk-1234"}`,
    },
    body: JSON.stringify({
      model: "gpt-4o",
      messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: prompt },
      ]
    }),
  });
}

5) We also want to get an input from the user.

const input = prompt("Hello! How can I help you today?");

6) Finally, we send the user's input into our fetchCompletion function and print the first choice returned by gpt-4o.

if (input) {
    // fetch and display the completion
    fetchCompletion(input)
    .then((response) => response.json())
    .then((data) => {
        console.log(data["choices"][0]["message"]["content"]);
    });
}

Trial Run

1) We can run our code from the terminal using deno run.

deno run main.ts

2) Now, permission is required because our application accesses the network. Deno prompts such permission requests when the application is trying to access sensitive API. For example, reading file systems and accessing networks. 

3) You can type "Y" to allow and continue running. You can also declare the permission when you execute the run command.

deno run --allow-net main.ts

4) Once the code executes, the result is rendered in the terminal. As expected.

Build & Deploy

1) We can build this little application and share it with our friends.

2) Run this compile command.

deno compile -R --allow-net main.ts

3) An executable file is created.

4) The executable does exactly what it is built for.


AI Summary AI Summary
gpt-4o-2024-08-06 2024-10-27 00:49:49
The article provides a concise guide to setting up and developing a simple Deno 2 application. It outlines steps to install Deno, create a command-line tool integrating OpenAI GPT models, and handle user input. Additionally, it covers running and granting permissions for the app, and details building the application into an executable for sharing.
Chrome On-device AI 2025-03-21 15:55:42

Share Share this Post