DEV Community

Alex Spinov
Alex Spinov

Posted on

Deno Has a Free API — Here's How to Use the Secure JavaScript Runtime

Deno is a secure JavaScript/TypeScript runtime with built-in tools. It runs TypeScript natively, has a standard library, and ships with a formatter, linter, and test runner.

Installation

curl -fsSL https://deno.land/install.sh | sh
Enter fullscreen mode Exit fullscreen mode

Running Code

deno run hello.ts                    # Run TypeScript directly
deno run --allow-net server.ts       # With network permission
deno run --allow-read --allow-write file.ts  # With file permissions
Enter fullscreen mode Exit fullscreen mode

HTTP Server

Deno.serve({ port: 3000 }, async (req) => {
  const url = new URL(req.url);

  if (url.pathname === "/api/hello") {
    return Response.json({ message: "Hello from Deno!" });
  }

  if (url.pathname === "/api/posts" && req.method === "POST") {
    const body = await req.json();
    return Response.json(body, { status: 201 });
  }

  return new Response("Not Found", { status: 404 });
});
Enter fullscreen mode Exit fullscreen mode

Standard Library

import { join } from "jsr:@std/path";
import { parse } from "jsr:@std/csv";
import { delay } from "jsr:@std/async";

// File operations
const content = await Deno.readTextFile("data.csv");
const records = parse(content, { skipFirstRow: true });
console.log(records);

await delay(1000);
const outPath = join(Deno.cwd(), "output.json");
await Deno.writeTextFile(outPath, JSON.stringify(records));
Enter fullscreen mode Exit fullscreen mode

Testing

import { assertEquals, assertRejects } from "jsr:@std/assert";

Deno.test("addition", () => {
  assertEquals(2 + 2, 4);
});

Deno.test("async test", async () => {
  const data = await fetchData();
  assertEquals(data.length, 10);
});

Deno.test("error handling", async () => {
  await assertRejects(() => fetchInvalid(), Error, "Not found");
});
Enter fullscreen mode Exit fullscreen mode
deno test
deno test --coverage
Enter fullscreen mode Exit fullscreen mode

KV Store (Built-in)

const kv = await Deno.openKv();

// Set values
await kv.set(["users", "1"], { name: "Alex", email: "alex@dev.com" });

// Get values
const entry = await kv.get(["users", "1"]);
console.log(entry.value); // { name: "Alex", ... }

// List values
const entries = kv.list({ prefix: ["users"] });
for await (const entry of entries) {
  console.log(entry.key, entry.value);
}
Enter fullscreen mode Exit fullscreen mode

Deploy to Deno Deploy

deno install -Agf jsr:@deno/deployctl
deployctl deploy --project=my-app --prod main.ts
Enter fullscreen mode Exit fullscreen mode

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)