How to use the Deno `std` library in NodeJS projects

2 min read

496 words

Hey there, NodeJS folks! Ever found yourself wishing you could use some of Deno's standard library features in your NodeJS project? Well, you're in luck! Today we're going to explore how to bring the best of both worlds together. Let's dive in!

Although the std library is primarily developed by the Deno maintainers, most of the modules are simply ESM modules that are not tied to the Deno runtime. They're usable in many other runtimes and even in the browser. Let's see how you can use these modules in your NodeJS project.

Locating the std library and it's modules

The std library is actively hosted on JSR, which is a package registry similar to npm. The good thing about JSR is that it only supports ESM modules. This way you can be sure that it is usable in modern NodeJS projects. To find them, go to jsr.io/@std/ and check out the available modules.

Installing and Importing Modules in NodeJS from JSR

To then use your desired module, JSR gives you a great hint and even the commands needed to set up the std module with your preferred package manager. In this case, we'll use npm since it's pretty much installed on every machine where NodeJS is installed.

Let's say we are trying to set up an HTTP call that we want to make reliable because we are contacting a source that may not be 100% available. The @std/async package has a retry method, which gives us a handy way to get a promise with a built-in retry mechanism that will try to contact the source n times before throwing an error.

Let's set this up. First, we need to install our @std/async package from JSR. The docs tells us to

npx jsr add @std/async

Use the @std/async module in NodeJS

If you’re not using a bundler or build tool that makes it possible to use ES modules be sure to set your "type": "module" in your package.json.

After running the command, we can see what the npx command does for us. As expected, it downloads the necessary files to our node_modules folder, adds an entry to our package.json as "@std/async": "npm:@jsr/std__async@^1.0.0-rc.2" and (if not already there) add a .npmrc telling npm where to look for the @jsr registry: @jsr:registry=https://npm.jsr.io.

Now to use our retry function, take the following code as an example to see how it works:

import { retry } from "@std/async

const fetch = async () => {
  throw new Error("error");
}

const main = async () => {
  try {
    await retry(fetch, { maxAttempts: 3 });
  } catch (e) {
    console.error(e.message)
  }
}

main();

This is the whole magic of setting up the std library in your NodeJS, pretty simple right? So go ahead and give it a try in your NodeJS project.

Thanks for reading & have a nice day! πŸ‘‹

Niklas