Getting started with deno.js🦕

Nikhil Sharma
2 min readJun 20, 2020

What’s this doc about? 🤔

This doc provides a quickstart intro for creating your first request using deno.js. I have tried to summarise the major points from the official docs provided by deno, but you can anyways dig deep into it, following the docs 🙂

I would soon be publishing another doc for a simple introduction on deno js runtime, which might help you gain a good context about the runtime and its motivation.

Note:- This doc is intended for those who wish to get onboarded fast on the deno environment and, hence provides the optimal info only for that purpose. It does not cover any further insights.

So let’s roll! 💃

Step 1: install deno

Step 2: create your first server using deno server file :-

Let’s understand the below-mentioned code:-

  • Unlike node.js, deno does not create a hefty node_modules folder. As you can see the import statement gets the dependencies from a hosted platform rather than a downloaded folder structure.
  • Next, we create a server using the serve function , by specifying the target port.
  • Don’t get scared of this weird for loop since its async iterators. This semantically means that the loop will run till the server if finished with its services which is not gonna happen ! So its sort of an infinite async loop.
// deno.tsimport { serve } from "https://deno.land/std@0.58.0/http/server.ts";
const s = serve({ port: 8000 });
console.log("http://localhost:8000/");for await (const req of s) {
req.respond({ body: "Hello World\n" });
}

Step 3: run the server

Note:- Since the deno claims to be a secure runtime, this means we need to explicitly give programs the permission to do certain ‘privileged’ actions, such as access to the network. So let’s add the allow-net flag for this.

>> deno run deno.ts --allow-net

Step 4: Creating our first request

let’s get started with creating our first GET request using deno API.

  • create the main file
import { Application } from "https://deno.land/x/oak/mod.ts";
import { APP_HOST, APP_PORT } from "./config.ts";
import router from "./routing.ts";

const app = new Application();

app.use(router.routes());
app.use(router.allowedMethods());

console.log(`Listening on ${APP_PORT}...`);

await app.listen(`${APP_HOST}:${APP_PORT}`);
  • Add a file for handling routes
//routing.tsimport { Router } from "https://deno.land/x/oak/mod.ts";
import getUsers from "./handlers/getUsers.ts";
import { fetchData } from "./db.ts";
import { User } from "../models/user.ts";
const router = new Router();
export const getUsers = async (): Promise<User[]> => {
const users = await fetchData();

// sort by name
return users.sort((a, b) => a.name.localeCompare(b.name));
};
router
.get("/users", async ({ response }) => {
response.body = await getUsers();
});


export default router;

--

--

Nikhil Sharma

Full stack Developer, making learning super easy for u and me !