Estimate project
← All posts

Picking a JavaScript Runtime in 2023: Node, Bun or Deno?

Node.js may be the de facto standard for server-side JavaScript, but it does not make everyone happy. This post takes a look at two alternative JavaScript runtimes, Deno and Bun. Are they going to replace Node.js one day? Is it worth giving them a go in your next project? Read on to find out!

11 min read
JavaScriptFrontendBackendFull stacktooling

According to Atwood’s law, every application that can be written in JavaScript eventually will be written in Javascript. The law was formulated two years before Node.js came into existence, and it proved to be exactly right. Once environments for executing JavaScript outside the browser appeared, people started building servers, CLIs and even machine learning algorithm models in plain JS.

Node.js may be the de facto standard for server-side JavaScript, but it does not make everyone happy – least of all its own author!

Node

Node, the first JS backend runtime, was created by Ryan Dahl in 2009. It is considerably older than its competitors and far more widely used. It is so well known, in fact, that there is little point in describing it at length. So let’s jump right to the summary:

Advantages:

  • Hugely popular → plenty of community projects, learning materials, job offers and so on
  • Generally pleasant and straightforward to work with

Disadvantages:

  • Executes only JavaScript – TypeScript projects need extra tooling like ts-node or swc-node
  • node_modules, vendored by default, occupy a lot of disk space and do not scale as the number of projects grows
  • Its API is incompatible with the browser API.

Deno

Deno is a runtime for JavaScript and TypeScript, likewise built by Ryan Dahl, though nearly 10 years later. It was meant to fix several of Node.js’s weak points, including its security model, its build system and the absence of built-in tooling.

Among its most important features are first-class TypeScript support, a linter, formatter and test runner included out of the box, and the option to bundle scripts into one JavaScript file or executable. Deno is becoming increasingly popular as a safer and less complicated alternative to Node.js.

Advantages:

  • TypeScript supported as a first-class citizen
  • Linter, formatter and test runner included
  • Designed with security as a priority
  • Works with many Node and npm Modules
  • Follows web platform standards for a better DX, e.g. fetch, WebSocket or even localStorage.

Disadvantages:

  • Far less popular than Node
  • Not fully mature yet; some APIs and methods are unstable or unfinished
  • At the moment, moving a Node project over to Deno can be really hard.

Let me walk you through a few features that I found particularly interesting.

Installation

First things first – we install Deno by running:

curl -fsSL https://deno.land/x/install/install.sh | sh

Other installation methods are described on Deno’s installation page.

Deno is nothing more than a single executable binary without any external dependencies. Once the script above has run and Deno has been added to the PATH variable, we are ready to go.

Next, we need to prepare the development environment in the IDE. For me, that simply meant installing the official Deno extension for VS Code and turning it on for my workspace.

Deno provides LSP integrations for a wide range of editors/IDEs, as well as CLI autocompletion’s for the popular shells. The complete list of integrations is available on this page.

First program

Time to write our first Deno program! The following example comes from the official documentation:

// main.ts
const url = Deno.args[0];
const res = await fetch(url);

const body = new Uint8Array(await res.arrayBuffer());
await Deno.stdout.write(body);

The program takes a URL from the command-line arguments, downloads the given website, turns it into a Uint8Array and writes it to the standard output.

Deno aims to rely on modern features and web standards whenever it can, so it comes as no surprise that top-level await works and that fetch is available without importing anything. Also worth noting is the Deno global variable, which exposes a wide range of server-side or Deno-specific APIs.

Security

Let’s run this code using deno run main.ts:

This brings us to another neat Deno feature. Scripts get no access to files, the network or even environment variables unless that access is explicitly granted. The reasoning is that your linter has no business sending data over the network or being able to write anywhere on your machine. Deno sandboxes scripts by default, and whenever a script needs some kind of access, you get asked for permission.

Naturally, we don’t need to be asked every single time. deno run accepts various flags that grant scripts fine-grained permissions. For instance, executing deno run --allow-net=example.com main.ts https://example.com lets the main.ts script access the network, but only the example.com domain.

TypeScript

Have you spotted that we just executed a TypeScript file without any fuss? Delivering a first-class experience for TypeScript development was one of Deno’s goals. Rather than configuring a transpilation step ourselves, as we would in a Node.js project, we let Deno handle everything. And it does so cleverly, maintaining a cache so that subsequent runs only check and transpile what actually needs it.

I’m a big fan of the choice to separate type checking from execution by default. Running a script with deno run script.ts transpiles it with swc and executes it with no type checking at all. To type check a module, we run deno check script.ts. Finally, both steps can be combined with deno run --check script.ts.

Separating the two is entirely sensible, because:

  • Type checking can take a long time
  • During development you frequently want to prototype and execute code that isn’t properly annotated yet.

Configuration file, tasks, and watch mode

Deno lets you put a configuration file named deno.json in the project root. It allows you to adjust the built-in TypeScript compiler, formatter and linter. For example:

{
  "compilerOptions": {
    "lib": ["deno.window"],
    "strict": true
  },
  "imports": {
    "std/": "https://deno.land/std@0.174.0/"
  },
  "tasks": {
    "dev": "deno run --watch src/hello.ts"
  },
  "lint": {
    "files": {
      "include": ["src/"],
      "exclude": ["src/testdata/"]
    },
    "rules": {
      "tags": ["recommended"],
      "include": ["ban-untagged-todo"],
      "exclude": ["no-unused-vars"]
    }
  },
  "fmt": {
    "files": {
      "include": ["src/"],
      "exclude": ["src/testdata/"]
    },
    "options": {
      "useTabs": true,
      "lineWidth": 80,
      "indentWidth": 4,
      "singleQuote": true,
      "proseWrap": "preserve"
    }
  }
}

The compilerOptions field configures TypeScript for the project. Most of the TS compiler options are supported by Deno.

The imports field allows us to define custom import mappings. Given the configuration above, for instance, we can write:

import { assertEquals } from "std/testing/assert.ts";

assertEquals(1, 2);

Rather than:

import { assertEquals } from "https://deno.land/std@0.174.0/testing/assert.ts";

assertEquals(1, 2);

lint and fmt configure the built-in linter and formatter, while tasks work like the scripts in package.json. They are executed with deno task <task_name>.

It’s nice that all the configuration lives in one file. As far as I can tell, the defaults are sensible, which helps keep that file short.

Another handy thing in Deno is the built-in --watch flag available for deno run, deno test, deno bundle and deno fmt. Deno users can do without nodemon.

Modules

Deno treats modules differently from Node.

  • Full file names are required – the file extension cannot be left out
  • index.js gets no special treatment
  • Third-party dependencies are imported by putting a URL in the import statement.
// local, filesystem import
import { add } from "./arithmetic.ts"

// remote import
import { multiply } from "https://x.nest.land/ramda@0.27.0/source/index.js";

In my view, this is among the biggest changes in thinking required when you begin working with Deno. If having all those links in import statements feels strange to you, you’re in good company. This is how the Deno team addresses it:

The way to go is to import your external libraries in one central deps.ts file and re-export them from there (it plays the same role as the package.json file in Node). Say, for instance, that the assertion library above is used throughout a big project. Instead of importing "https://deno.land/std@0.177.0/testing/asserts.ts" in every place, you can create a deps.ts file that exports the third-party code.

Testing

As you might expect by now, Deno comes with a built-in test runner of its own. Compared to something like Jest, it is fairly minimal, offering mainly an API for declaring tests and test steps. Assertions, test setups and tear-downs are meant to be written in vanilla JS rather than with the it.is.not.equal chaining style other frameworks have made us used to.

In some ways it resembles testing in Rust. Unlike in Rust, though, test cases cannot live in the same file as the implementation. As far as I could see, Deno searches for tests in *.test.{ts,js,tsx,jsx} and a handful of other globs, and ignores any other Deno.test occurrences.

This is a bit of a letdown for me, since I enjoy the DX of keeping unit tests right next to the implementation. I make good use of it in Node-based projects with Vitest and, obviously, in Rust. Given how much of Deno’s tooling appears to draw on the Rust ecosystem, I expected this feature to be there too.

Interoperating with Node.js and npm

Starting with version 1.28, npm packages can be used in Deno projects through npm: specifiers, like this:

import lodash from "npm:lodash@^4.17";

console.log(lodash.map([1, 2, 3], (n) => n * 2));

When a package is written in TypeScript or ships its own types, everything behaves as expected. When it doesn’t ship types, however, we may run into problems:

import lodash from "npm:lodash@^4.17";

console.log(lodash.map([1, 2, 3], (n) => n * 2));
//                                 ^ error here:
// Parameter 'n' implicitly has an 'any' type.deno-ts(7006

Fortunately, a @deno-types directive solves this, much like installing extra types as dev dependencies in Node:

// @deno-types="npm:@types/lodash"
import lodash from "npm:lodash@^4.17";

console.log(lodash.map([1, 2, 3], (n) => n * 2));
//                                 ^ n is inferred as a number, Nice!

Deno may look fantastic, but bear in mind that npm package support is still being developed. Certain packages may not run under Deno, and tools such as deno bundle and deno compile also fail in projects that rely on npm: specifiers.

Still, I’m glad that work on a Node–Deno compatibility layer is under way, because for many developers considering the move, it is a decisive factor.

Bun

Bun is the newest arrival. Although it is still baking, plenty of people are already excited about it. On the subject of baking, Oven is the name of the company set up by Bun’s author, Jarred Sumner. It has secured $7 million in funding in order to “drive Bun’s development, provide hosting, and turn Bun into an end-to-end JavaScript solution,” as stated on its website.

Bun pursues three main goals:

  • Run JavaScript as quickly as possible
  • Deliver excellent, comprehensive and fast tooling (bundler, package manager, etc.)
  • Work as a drop-in replacement for every existing Node project.

Clearly, its approach is very different from Deno’s. Rather than reimagining how different the ideal server-side JavaScript experience might be, Jarred Sumner focuses on how fast (and also how enjoyable) that experience can become.

Performance

Deno relies on V8, the same JavaScript execution engine that Node uses, but Jarred observed that the engine of WebKit (Safari), JavaScriptCore, is usually somewhat faster and uses memory more efficiently. Embedding JSC in a runtime is harder, however, which is why V8 is the usual pick. Jarred isn’t one to shy away from effort, though, and his main goal is obvious: pushing JavaScript performance to a new level.

That covers only the execution engine, though. What makes the remaining parts of the runtime so quick? Benchmarking and optimizing everything that can possibly be optimized. Bun is implemented in Zig, a low-level language with manual memory management that makes it possible to write extremely fast code, but also… to introduce bugs that make the program segfault. And right now there are plenty of those.

Fortunately, every release fixes many bugs and makes Bun faster still!

Tooling and developer experience

Despite being at an early stage, Bun already offers an impressive set of tools.

To begin with, Bun can serve as a package manager compatible with npm. I tried it on a fairly big repository that needs more than 3,000 packages installed, and these are the results:

  • yarn (no yarn.lock) → 236 s
  • yarn (with yarn.lock) → 63 s
  • bun install (no bun.lockb) → 21 s
  • bun install (with bun.lockb) → 6.77 s

Impressive – that’s a 10x speed-up!

Bun also works as a task runner. Simply executing bun run start rather than npm run start saves you more than 150 ms of overhead introduced by npm.

Bun additionally offers a test runner that is moving towards full Jest compatibility.

To speed up development, you can use the tools mentioned above, along with Bun’s own bundler and transpiler, without having to use Bun as your runtime!

Summary

To sum up, Node.js is the most popular option for running JavaScript on the server today, backed by an enormous community and a wealth of resources.

Deno, however, is a promising newcomer that brings better security and a better development experience, particularly for TypeScript projects.

Bun is still early in its development, but it strives to deliver the fastest possible JavaScript execution together with a full toolset, which makes it an attractive choice for anyone focused on performance.