Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

deno
typescript
web development
http

How to set up an HTTP Hello World server in Deno

Educative Answers Team

Hello World Server

A Hello World server is a basic HTTP server that returns the text, “Hello World” for any request made to it.

The main purpose of making such a server is to gain some familiarity with setting up servers.

Code

The following example shows the code used to design this server.

import { serve } from "https://deno.land/std/http/server.ts";

// Defining port to be used
const PORT = 8080
// Setting server to listen at port
const server = serve({ port: PORT });
console.log(`This Hello World server is up and running on http://localhost:${PORT}/`);

// Sending Hello World to any client that connects
for await (const req of server) {
  req.respond({ body: "Hello World!\n" });
}

This program defines the PORT variable as 8080, sets the server to listen at this port, and then responds to each connection with Hello World.

The serve library uses an async generator to return any requests made to the server. Hence, the for await loop simply gets those requests and sends back Hello World! without differentiating between them.

To run the app, use the following command-line script.

deno run --allow-net --allow-read hello_world.ts

The --allow-net flag allows Deno to use the network and the --allow-read flag allows Deno to read the file system. Since Deno is strict about security, both permissions are required for this server.

Another way to run this program is to run the following script.

deno run hello_world.ts

However, since this does not include the permission flags, Deno will ask the user for both permissions before running the program.

RELATED TAGS

deno
typescript
web development
http
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring