DevToolBoxGRÁTIS
Blog

Guia Completo Deno 2: Compatibilidade Node.js e npm

14 minby DevToolBox

Deno 2 represents a major evolution in the JavaScript and TypeScript runtime landscape. With full Node.js compatibility, native npm package support, and a refined developer experience, Deno 2 bridges the gap between the modern runtime vision and the practical needs of existing Node.js ecosystems. This guide covers everything you need to know about Deno 2, from its new features to migration strategies.

What Is New in Deno 2

Deno 2 introduces several groundbreaking changes that make it a practical choice for production applications. The most significant change is backward compatibility with Node.js and npm, which removes the biggest barrier to adoption.

Full Node.js Compatibility

Deno 2 includes a Node.js compatibility layer that supports the vast majority of Node.js built-in modules including fs, path, http, crypto, stream, and child_process. You can import Node.js modules using the node: prefix, and most npm packages work without modification.

// Using Node.js built-in modules in Deno 2
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { createHash } from "node:crypto";
import { EventEmitter } from "node:events";

const content = readFileSync(join(".", "config.json"), "utf-8");
const hash = createHash("sha256").update(content).digest("hex");
console.log("Config hash:", hash);

// Node.js streams work too
import { Readable, Transform } from "node:stream";
const readable = Readable.from(["hello", "world"]);

Native npm Support

Deno 2 can import npm packages directly using the npm: specifier. No node_modules directory is created by default - packages are cached globally. You can also use a package.json if you prefer the traditional Node.js workflow.

// Import npm packages directly
import express from "npm:express@4";
import { z } from "npm:zod";
import chalk from "npm:chalk@5";
import _ from "npm:lodash";

// Or use an import map in deno.json
// deno.json:
// {
//   "imports": {
//     "express": "npm:express@4",
//     "zod": "npm:zod",
//     "chalk": "npm:chalk@5"
//   }
// }

// Then import normally:
// import express from "express";

Refined Permission System

Deno retains its security-first permission system but now supports more granular controls. You can allow specific file paths, network hosts, and environment variables. The --allow-all flag grants all permissions for development convenience.

# Granular permissions
deno run --allow-read=./data --allow-write=./output server.ts
deno run --allow-net=api.example.com:443 fetch.ts
deno run --allow-env=DATABASE_URL,API_KEY app.ts

# Allow all permissions (development only)
deno run --allow-all server.ts
# Or use the shorthand
deno run -A server.ts

# Run with no permissions (most secure)
deno run sandboxed.ts

Standard Library Updates

The Deno standard library has been stabilized with clear versioning. Key modules include @std/fs for file operations, @std/http for HTTP servers, @std/testing for test utilities, and @std/async for async helpers.

// Deno standard library (jsr:@std/)
import { ensureDir, copy } from "jsr:@std/fs";
import { parse } from "jsr:@std/flags";
import { assertEquals } from "jsr:@std/assert";
import { delay } from "jsr:@std/async";

await ensureDir("./output");
await copy("./src", "./output/src", { overwrite: true });

const args = parse(Deno.args, {
  string: ["port"],
  default: { port: "3000" },
});

Getting Started with Deno 2

Installing and running Deno 2 is straightforward. Deno ships as a single binary with no external dependencies.

# Install Deno
curl -fsSL https://deno.land/install.sh | sh    # macOS/Linux
irm https://deno.land/install.ps1 | iex          # Windows

# Verify installation
deno --version
# deno 2.x.x
# v8 12.x.x
# typescript 5.x.x

# Create a new project
deno init my-project
cd my-project

# Run a TypeScript file directly
deno run main.ts

# Run with watch mode
deno run --watch main.ts

# Format, lint, and test
deno fmt
deno lint
deno test

Configuration with deno.json

Deno 2 uses deno.json (or deno.jsonc) for project configuration. This file replaces the need for tsconfig.json, package.json (optionally), and various tool configs.

// deno.json
{
  "tasks": {
    "dev": "deno run --watch --allow-all main.ts",
    "start": "deno run --allow-net --allow-read main.ts",
    "test": "deno test --allow-all",
    "build": "deno compile --output=app main.ts"
  },
  "imports": {
    "@std/http": "jsr:@std/http@^1.0.0",
    "@std/assert": "jsr:@std/assert@^1.0.0",
    "express": "npm:express@4",
    "zod": "npm:zod@^3.22"
  },
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "react"
  },
  "fmt": {
    "semiColons": true,
    "singleQuote": true,
    "lineWidth": 100
  },
  "lint": {
    "rules": {
      "tags": ["recommended"]
    }
  }
}

Migrating from Node.js

Migrating an existing Node.js project to Deno 2 is more practical than ever. Here is a step-by-step approach.

Step 1: Add deno.json

Create a deno.json file in your project root. You can keep your existing package.json alongside it during the transition.

Step 2: Update Imports

Convert Node.js built-in imports to use the node: prefix. Update npm package imports to use the npm: specifier or keep using bare specifiers with an import map.

// Before (Node.js)
const fs = require("fs");
const path = require("path");
const express = require("express");

// After (Deno 2)
import fs from "node:fs";
import path from "node:path";
import express from "npm:express@4";

// Or use Deno-native APIs
const content = await Deno.readTextFile("./config.json");
const joined = new URL("./data/file.txt", import.meta.url);

Step 3: Handle CommonJS

Deno 2 supports CommonJS modules through the node: compatibility layer. For your own code, convert require() calls to ESM import statements. For dependencies, most work automatically.

Step 4: Update Scripts

Replace npm scripts with Deno tasks in deno.json. Deno tasks support shell-like syntax and can run any command.

// package.json scripts:
// "scripts": {
//   "dev": "nodemon server.ts",
//   "test": "jest",
//   "build": "tsc && node dist/index.js"
// }

// deno.json tasks:
// "tasks": {
//   "dev": "deno run --watch --allow-all server.ts",
//   "test": "deno test --allow-all",
//   "build": "deno compile --output=app server.ts"
// }

Web Frameworks in Deno 2

Deno 2 supports multiple approaches to building web applications, from the built-in Deno.serve() to popular frameworks.

Deno.serve() (Built-in)

// Simple HTTP server with Deno.serve()
Deno.serve({ port: 3000 }, async (req: Request) => {
  const url = new URL(req.url);

  if (url.pathname === "/api/hello") {
    return Response.json({ message: "Hello from Deno 2!" });
  }

  if (url.pathname === "/api/data" && req.method === "POST") {
    const body = await req.json();
    return Response.json({ received: body }, { status: 201 });
  }

  return new Response("Not Found", { status: 404 });
});

console.log("Server running on http://localhost:3000");

Express.js Compatibility

Thanks to npm compatibility, you can run Express.js applications directly in Deno 2 with minimal changes.

// Express.js running in Deno 2
import express from "npm:express@4";
import cors from "npm:cors";

const app = express();
app.use(cors());
app.use(express.json());

app.get("/api/users", (_req, res) => {
  res.json([
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
  ]);
});

app.listen(3000, () => {
  console.log("Express on Deno 2: http://localhost:3000");
});

Testing in Deno 2

Deno includes a built-in test runner with support for assertions, mocking, benchmarking, and code coverage. No additional test framework is needed.

// math.test.ts
import { assertEquals, assertThrows } from "jsr:@std/assert";

function add(a: number, b: number): number {
  return a + b;
}

Deno.test("add function", () => {
  assertEquals(add(2, 3), 5);
  assertEquals(add(-1, 1), 0);
  assertEquals(add(0, 0), 0);
});

Deno.test("async test", async () => {
  const response = await fetch("https://api.example.com/data");
  assertEquals(response.status, 200);
});

Deno.test({
  name: "test with permissions",
  permissions: { read: true, net: false },
  fn() {
    const data = Deno.readTextFileSync("./test-data.txt");
    assertEquals(data.length > 0, true);
  },
});

// Run: deno test
// Run with coverage: deno test --coverage=./cov

Deployment Options

Deno 2 applications can be deployed to various platforms including Deno Deploy (edge), Docker containers, traditional VPS, and serverless platforms.

Deno Deploy

Deno Deploy is a globally distributed edge hosting platform designed specifically for Deno. It offers zero-config deployment, automatic HTTPS, and sub-millisecond cold start times.

# Install deployctl
deno install -A jsr:@deno/deployctl

# Deploy to Deno Deploy
deployctl deploy --project=my-app main.ts

# Or link to GitHub for automatic deployments

Docker Deployment

Deno works well in Docker containers. The official Deno Docker image is lightweight and production-ready.

# Dockerfile for Deno 2
FROM denoland/deno:2.0.0

WORKDIR /app

# Cache dependencies
COPY deno.json deno.lock ./
RUN deno install

# Copy source
COPY . .

# Cache the main module
RUN deno cache main.ts

EXPOSE 3000

CMD ["deno", "run", "--allow-net", "--allow-read", "--allow-env", "main.ts"]

Frequently Asked Questions

Can I use my existing npm packages with Deno 2?

Yes. Deno 2 supports npm packages natively using the npm: specifier. The vast majority of npm packages work without modification, including popular ones like express, prisma, next, and react.

Is Deno 2 production-ready?

Yes. Deno 2 is designed for production use. Companies like Slack, Netlify, and Supabase use Deno in production. The runtime has been battle-tested and the stability guarantees are clear.

Should I migrate from Node.js to Deno 2?

For new projects, Deno 2 is an excellent choice with better defaults (TypeScript, security, modern APIs). For existing projects, migration is practical but optional. Consider migrating if you want better security, native TypeScript support, or a more modern developer experience.

How does Deno 2 compare to Bun?

Both are modern JavaScript runtimes. Bun focuses on raw speed and Node.js drop-in compatibility. Deno focuses on security (permission system), web standards compliance, and TypeScript-first development. Deno 2 has better security defaults; Bun has faster startup and bundling.

Does Deno 2 support TypeScript out of the box?

Yes. Deno supports TypeScript natively without any configuration. You can run .ts and .tsx files directly. Type checking can be enabled with the --check flag.

𝕏 Twitterin LinkedIn
Isso foi útil?

Fique atualizado

Receba dicas de dev e novos ferramentas semanalmente.

Sem spam. Cancele a qualquer momento.

Try These Related Tools

JSTypeScript to JavaScript{ }JSON Formatter

Related Articles

Bun vs Node.js vs Deno 2026

Compare runtimes JavaScript.

TypeScript 5 Novidades: Decoradores, Const Type Params e Satisfies

Guia completo das novidades TypeScript 5: decoradores, const type params e satisfies.