How to Add a Third Party Library in Deno.js?


To add a third-party library in Deno, we need to import the library from its URL. We can use the "import" statement followed by the URL of the library. It is also possible to use a local file path instead of a URL. The library can then be used in our code by referencing its exported functions or variables. Let us first understand what is Deno.js −

What is Deno.js?

  • Deno is a new JavaScript/TypeScript runtime built with V8 JavaScript engine.

  • It is built on top of Rust programming language and uses the Tokio library for asynchronous I/O.

  • Unlike Node.js, Deno does not use a package manager, instead it uses standard import statements to load modules.

  • Deno has built-in support for web development, testing, formatting, and linting.

  • Deno is still in its early stages but is gaining popularity as a more secure and performant alternative to Node.js.

Approach

  • First, locate the library you want to use on a website such as Deno.land.

  • Once you have found the library, you can use the "import" statement to import it into your project. For example, if you want to import the "http" library, you would use the following code: import * as http from https://deno.land/std/http/mod.ts

  • Once you have imported the library, you can use its functions and methods within your code.

  • Finally, make sure to run your project with the "--allow-net" flag if the library requires network access.

For example − deno run --allow-net your_script.ts

Note − Make sure you have the latest version of Deno installed on your system before running the project.

Example

Here is a complete example of importing and using the "http" library from Deno.land in a Deno project −

import { serve } from https://deno.land/std/http/server.ts;
const server = serve({ port: 8000 });
console.log("Server running on http://localhost:8000);
for await (const req of server) {
   req.respond({ body: "Hello Deno!" });
}

This example creates a simple HTTP server that listens on port 8000 and responds with "Hello Deno!" to every incoming request.

To run this example, save the code in a file named "server.ts" and run the following command in your terminal −

deno run --allow-net server.ts

This will start the server and you can test it by visiting http://localhost:8000 in your web browser.

Output

Updated on: 13-Feb-2023

191 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements