Rust for Node.js developers: ownership, Result and async side by side
Rust for Node.js developers: TypeScript next to Rust for ownership, Option, Result, traits, lazy futures and Cargo, with tested examples and a migration checklist.
Editorial date · 15 min read · Published
Rust for Node.js developers: what changes first
Rust for Node.js developers is less about new syntax than about decisions that JavaScript makes for you. In Node.js, V8 decides when memory is freed, any function may throw, a Promise starts running as soon as it is created, and TypeScript's types disappear before the code runs. Rust moves each of those decisions into code the compiler checks: an owner frees each value at a known point, failure is part of the return type, a future does nothing until it is polled, and types survive into the compiled program. Whether you are looking for Rust for JavaScript developers or for a route from TypeScript to Rust, these are the four shifts to learn first.
This guide follows the free Crabrix course Rust for Node.js Developers: 20 lessons in five units, each of which puts a Node.js habit next to its Rust counterpart, names exactly what changes and ends with a small port. Many lessons credit the Academy lessons that cover the same ground in more depth, and we link both kinds below.
Every Rust program in this article was compiled and run with rustc 1.99.0 in edition 2024, and also checked for wasm32-wasip1, the target the Crabrix Playground compiles to. Every TypeScript snippet passed tsc --strict (version 5.9) and ran on Node.js 22.13, and quoted output comes from those runs. Similar constructs are not identical, so each section says where the comparison stops.
Original generated illustration: leaving the always-turning event loop for a workshop where every tool has one owner and a place to be put away.
From TypeScript to Rust: types that are checked, not erased
node app.js starts a runtime: V8 interprets your file and compiles hot functions while it runs, and Node.js supplies the event loop and the garbage collector. cargo build works ahead of time and writes a native executable, or a WebAssembly module, that runs without Rust or Node.js installed. A typo in an untested branch is a TypeError in JavaScript on the day that branch runs; in Rust it stops the build. Our test with sum.to_strng() failed with E0599, no method named to_strng found for type u32 in the current scope, and rustc suggested to_string.
TypeScript narrows the gap, but its types are erased. The snippet below passes tsc --strict, yet JSON.parse(raw) as User is an assertion that nothing verifies: user.id + 1 printed string 421, and the value typed any failed at runtime with Cannot read properties of null (reading 'toUpperCase'). Rust has no any. Its as is a real conversion between primitive types, such as u64 to u32, which truncates, and casting a &str to a u32 does not compile. Outside text becomes a typed value only through a step that returns a Result, such as parse or serde_json::from_str.
Read each arrow in the infographic as 'is replaced by a different design', not 'is the same as'. The sections that follow pair a short TypeScript snippet with the Rust code that replaces it.
interface User {
id: number;
name: string;
}
const raw = '{"id": "42", "name": null}';
const user = JSON.parse(raw) as User; // an assertion that nothing checks
console.log(typeof user.id, user.id + 1); // string 421const label: any = user.name;
try {
console.log(label.toUpperCase()); // type-checks, fails at runtime
} catch (err) {
console.log((err as Error).message);
}
Original generated infographic: three TypeScript habits and the Rust designs that replace them, null with Option, throw with Result and Promise with Future.
In JavaScript, assignment copies a reference. Below, alias and order name one object, the spread copy shallow is a new outer object that still shares the items array, and addItem changes the caller's data without saying so in its signature; all three views printed the same two items. Nothing in the code decides when the object is freed. V8's garbage collector reclaims it some time after the last reference disappears, and a FinalizationRegistry callback for it may run late or never.
That is convenient for memory and awkward for everything else: files, sockets and locks still need close() or try/finally. Rust replaces the collector with a rule the compiler enforces. Every value has exactly one owner, and when the owner goes out of scope the value is dropped: its Drop implementation runs, its fields are dropped and its memory is released, at a line you can point to. The same mechanism closes a File, releases the lock held by a MutexGuard and frees a Vec, and there are no collection pauses.
type Order = { id: number; items: string[] };
function addItem(order: Order, item: string): void {
order.items.push(item); // changes the caller's object
}
function archive(order: Order): string {
return`archived #${order.id} with ${order.items.length} items`;
}
const order: Order = { id: 7, items: ["tea"] };
const alias = order; // a second reference to the same objectconst shallow = { ...order }; // a new outer object, same items array
addItem(alias, "cake");
console.log(archive(order)); // archived #7 with 2 items
console.log(shallow.items); // [ 'tea', 'cake' ]// `order` is still usable; V8 frees it some time after the last reference goes
Ownership in Rust: moves, borrows and a drop you can predict
The Rust version puts each choice in a signature. add_item takes &mut Order, an exclusive borrow for the duration of the call, and the call site repeats it as &mut order. count takes &Order, a shared borrow that can only read. archive takes Order by value, so archive(order) moves ownership into the function. The move copies the struct itself, an integer plus the Vec's pointer, capacity and length, not the strings, and from that line on order is unusable in main.
Because archive owns the order, drop order #7 (2 items) printed as archive returned, before main printed the receipt. The clone, renumbered to 8, has its own Vec and Strings, which makes it closer to structuredClone than to spread, and it was dropped at the closing brace of main. When we added a line that read order.id after the move, rustc refused with E0382, borrow of moved value: order, pointed at archive(order) and suggested borrowing or cloning instead.
Borrowing has one rule: any number of shared references &T or exactly one mutable reference &mut T, never both at once. It rules out the habit of appending to an array while a loop walks it, which is E0502 in Rust. Ask for the least access a function needs: &str or &[T] to read, &mut to change, and a value only when the function must keep or consume the data. Small Copy types such as integers and bool are duplicated on assignment, so nothing moves.
#[derive(Clone, Debug)]struct Order {
id: u32,
items: Vec<String>,
}
impl Drop for Order {
fn drop(&mutself) {
println!("drop order #{} ({} items)", self.id, self.items.len());
}
}
fn add_item(order: &mut Order, item: &str) {
order.items.push(item.to_string()); // exclusive borrow, only for this call
}
fn count(order: &Order) -> usize {
order.items.len() // shared borrow: read only
}
fn archive(order: Order) -> String {
format!("archived #{} with {} items", order.id, order.items.len())
} // `archive` owns `order`, so it is dropped herefn main() {
letmut order = Order { id: 7, items: vec![String::from("tea")] };
add_item(&mut order, "cake");
letmut copy = order.clone(); // an independent copy, Vec and Strings included
copy.id = 8;
println!("{} items", count(&order));
let receipt = archive(order); // move: `order` cannot be used after this lineprintln!("{receipt}");
println!("end of main");
} // `copy` is dropped here
Original generated illustration: a move hands the one parcel to the next function, leaving only an outline behind, and the new owner releases it when done.
With strictNullChecks, TypeScript marks absence in types such as number | undefined, and ?. and ?? make optional data pleasant to read. Three problems remain. A missing property, undefined and null are different runtime values behind one optional type. The checks vanish after compilation, so data from outside can break them. And || falls back on every falsy value, so the buggy version below turns a configured 0 into 3: the snippet printed 3 0 3. Map.get with optional chaining printed undefined without complaint, which is convenient until that value reaches an addition and becomes NaN.
Rust has no null. A value that may be missing has type Option<T>, either Some(value) or None, and cannot be used as a T until you decide what absence means: adding 1 to an Option<u32> is E0369, cannot add {integer} to Option<u32>. The operators become methods. a?.b is as_ref().and_then(...) when b is itself optional, or map when it is not, and x ?? 3 is unwrap_or(3), or unwrap_or_else when the default is expensive to build.
unwrap_or replaces only None, so Some(0) stays 0 and the example printed 3 0, like the correct TypeScript version rather than the || one. HashMap::get returns an Option too, and the match must handle both arms. Inside a function that returns Option, ? returns None early, which is why first_word_len(" ") printed None. Option says whether a value is there, not why it is missing. When the caller needs a reason, return Result, or Result<Option<T>, E> when absence is normal and failure is a separate case.
throw and try/catch: failure the signature does not show
In JavaScript any function may throw anything, and nothing in its type says so: parsePort declares number, and callers learn about the exception by reading its body or watching it fail. The parsing is lenient as well. Number("") is 0, which the range check happens to reject, but Number("0x50") is 80, so the hexadecimal string was accepted as port 80. In strict TypeScript the catch variable has type unknown, hence err as Error.
Teams work around the silent signature with @throws comments or returned { ok, error } objects. Rust builds that idea into the language: you cannot reach the value without deciding what to do about the error, and a Result that is ignored triggers a compiler warning.
function parsePort(text: string): number {
const n = Number(text);
if (!Number.isInteger(n) || n < 1 || n > 65535) {
thrownew Error(`invalid port: ${JSON.stringify(text)}`);
}
return n;
}
for (const input of ["8080", "", "0x50", "70000"]) {
try {
console.log(JSON.stringify(input), "->", parsePort(input));
} catch (err) {
console.log(JSON.stringify(input), "->", (err as Error).message);
}
}
parse_port returns Result<u16, PortError>, either Ok(port) or Err(reason). The error is an enum you design, so callers tell NotANumber from OutOfRange with match instead of comparing message strings, and NotANumber keeps the original ParseIntError as its cause. Parsing is strict: the empty string gave cannot parse integer from empty string, and 0x50 gave invalid digit found in string. One surprise runs the other way, because integer parse accepts a leading plus sign: "+8080" parsed as 8080 in our test, so validate the format first if your contract forbids a sign.
? is the visible form of exception propagation. In parse_port, text.parse().map_err(PortError::NotANumber)? returns early with the wrapped error. In listen_address, split_once(':') gives an Option, ok_or turns it into a Result, and ? converts the error through From into the function's String error type. ? compiles only where the return type can carry the error, so every call that can fail is marked. The run printed Ok("localhost:3000"), an Err naming the port for localhost:0, and Err("expected host:port").
Panics are not exceptions either. unwrap(), expect(), an out-of-bounds index and integer overflow in a debug build all panic, which unwinds the thread or aborts the process. Keep them for bugs and use Result for anything a caller can reasonably handle: bad input, a missing file, a refused connection.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]enum PortError {
NotANumber(ParseIntError),
OutOfRange(u32),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
matchself {
PortError::NotANumber(e) => write!(f, "not a number: {e}"),
PortError::OutOfRange(n) => write!(f, "{n} is outside 1..=65535"),
}
}
}
fn parse_port(text: &str) -> Result<u16, PortError> {
let n: u32 = text.parse().map_err(PortError::NotANumber)?;
matchu16::try_from(n) {
Ok(port) if port != 0 => Ok(port),
_ => Err(PortError::OutOfRange(n)),
}
}
fn listen_address(spec: &str) -> Result<String, String> {
let (host, port) = spec.split_once(':').ok_or("expected host:port")?;
let port = parse_port(port).map_err(|e| format!("port {port:?}: {e}"))?;
Ok(format!("{host}:{port}"))
}
fn main() {
for input in ["8080", "", "0x50", "70000"] {
match parse_port(input) {
Ok(port) => println!("{input:?} -> {port}"),
Err(err) => println!("{input:?} -> {err}"),
}
}
println!("{:?}", listen_address("localhost:3000"));
println!("{:?}", listen_address("localhost:0"));
println!("{:?}", listen_address("localhost"));
}
TypeScript interfaces are structural. The two object literals below have no implements clause, yet both are Shapes because they have area and name with compatible types: duck typing with a compiler. On a class, implements is an extra check rather than the thing that creates the relationship. A Shape[] can mix any such objects, and each call is looked up on the object at runtime. The snippet printed rect undefined. Rust takes the opposite position.
interface Shape {
area(): number;
name(): string;
}
// No `implements`: any value with these members is a Shape.const square = { side: 3, area() { return this.side * this.side; }, name: () => "square" };
const rect = { w: 2, h: 5, area() { return this.w * this.h; }, name: () => "rect" };
function largest(shapes: Shape[]): string | undefined {
let best: Shape | undefined;
for (const s of shapes) if (!best || s.area() > best.area()) best = s;
return best?.name();
}
console.log(largest([square, rect]), largest([])); // rect undefined
Traits in Rust: explicit implementations, static or dynamic dispatch
Rust traits are nominal. Square is a Shape only because of impl Shape for Square; an inherent area method with the same signature does not count, and passing such a type where a Shape is required is E0277, the trait bound is not satisfied. Default methods such as describe take the place of a shared base class, and implementing standard traits such as Display plugs a type into existing generic code. A discriminated union, by contrast, becomes an enum rather than a trait.
How you use a trait is a design decision. total_area<T: Shape> is generic, like <T extends Shape>, but it is compiled separately for each concrete type and dispatched statically, so every item in the slice must be the same type. largest takes &[Box<dyn Shape>], trait objects that carry a pointer to the value and to a table of its methods, which is how a mixed TypeScript array behaves. The program printed Some("rect with area 10") None, then 5. Neither form is automatically faster: generics can increase code size, and trait objects add an indirection.
trait Shape {
fn area(&self) -> u32;
fn name(&self) -> &str;
// A default method, shared by every implementation.fn describe(&self) -> String {
format!("{} with area {}", self.name(), self.area())
}
}
struct Square { side: u32 }
struct Rect { w: u32, h: u32 }
impl Shape for Square {
fn area(&self) -> u32 { self.side * self.side }
fn name(&self) -> &str { "square" }
}
impl Shape for Rect {
fn area(&self) -> u32 { self.w * self.h }
fn name(&self) -> &str { "rect" }
}
// Generic: compiled once per concrete T; every item is the same T.fn total_area<T: Shape>(items: &[T]) -> u32 {
items.iter().map(|s| s.area()).sum()
}
// Trait objects: a mixed list, dispatched at runtime.fn largest(shapes: &[Box<dyn Shape>]) -> Option<String> {
shapes.iter().max_by_key(|s| s.area()).map(|s| s.describe())
}
fn main() {
let mixed: Vec<Box<dyn Shape>> = vec![Box::new(Square { side: 3 }), Box::new(Rect { w: 2, h: 5 })];
println!("{:?} {:?}", largest(&mixed), largest(&[]));
println!("{}", total_area(&[Square { side: 2 }, Square { side: 1 }]));
}
Calling an async function in JavaScript runs its body synchronously up to the first await, and the event loop built into Node.js drives the rest. That is why the snippet printed fetching 1 and fetching 2 before both promises created, and why fetchPrice(3) logged although nothing awaited it. A Promise is work that has already started. Promise.all starts nothing; it waits for promises that are already running.
Nor can a Promise be cancelled from outside: an AbortSignal only asks the called code to stop, and it may not listen. Because the event loop belongs to the runtime, a Node.js program never has to choose an executor.
asyncfunction fetchPrice(id: number): Promise<number> {
console.log(`fetching ${id}`); // runs as soon as fetchPrice() is calledreturn40 + id;
}
asyncfunction total(): Promise<number> {
const a = fetchPrice(1); // already runningconst b = fetchPrice(2); // already running
console.log("both promises created");
return (await a) + (await b);
}
const pending = total();
console.log("created");
pending.then((sum) => console.log(`total = ${sum}`));
void fetchPrice(3); // runs too, although nothing awaits it
Async in Rust: lazy futures and a runtime such as Tokio
Calling a Rust async fn runs nothing. It returns a Future, a state machine that makes progress only when it is polled, normally through .await, and Rust has no built-in event loop to do the polling. Here a ten-line block_on polls in a loop with a no-op waker, which suits only futures that never wait for I/O. The output reverses the JavaScript order: created and both futures created printed before fetching 1, and the dropped future never printed fetching 3. Calling save("invoice-7"); without .await made rustc warn: unused implementer of Future that must be used, with the note futures do nothing unless you .await or poll them.
Real programs use a runtime. With Tokio and its macros, rt-multi-thread and time features, you mark async fn main with #[tokio::main]; the executor polls your futures and uses each Waker to resume work when a socket or timer is ready. The counterparts are close, not equal. a.await + b.await runs two futures in sequence. tokio::join!(a, b) polls both concurrently inside one task, the usual replacement for Promise.all. tokio::spawn starts a separate task without being awaited, possibly on another worker thread, so its future must be Send and 'static.
Laziness also gives Rust cancellation: a dropped future is never polled again, and its local values are dropped. That is how tokio::time::timeout and select! cancel work. In a separate offline Cargo run with Tokio 1.54.1, join! completed both calls, and a 60 ms timeout around a 150 ms call reported the timeout after dropping the inner future. Keep data consistent between .await points, because a future can stop at any of them.
use std::future::Future;
use std::pin::pin;
use std::task::{Context, Poll, Waker};
asyncfn fetch_price(id: u32) -> u32 {
println!("fetching {id}");
40 + id
}
asyncfn total() -> u32 {
let a = fetch_price(1); // nothing runs yetlet b = fetch_price(2);
println!("both futures created");
a.await + b.await// one after the other, not like Promise.all
}
// A minimal executor for futures that never wait on I/O.// Real programs use a runtime such as Tokio instead.fn block_on<F: Future>(future: F) -> F::Output {
letmut future = pin!(future);
letmut cx = Context::from_waker(Waker::noop());
loop {
iflet Poll::Ready(value) = future.as_mut().poll(&mut cx) {
return value;
}
}
}
fn main() {
let pending = total();
println!("created");
println!("total = {}", block_on(pending));
let unused = fetch_price(3);
drop(unused); // never polled: "fetching 3" is never printed
}
Cargo vs npm: Cargo.toml, Cargo.lock and version requirements
Cargo.toml plays the part of package.json, with [dependencies] and [dev-dependencies] sections, and Cargo.lock records the resolved versions like package-lock.json; commit it for applications. Crate sources are cached once per user under ~/.cargo/registry and build output goes to target/, so there is no node_modules. cargo add serde does the job of npm install serde, cargo build fetches whatever is missing, and run, test, check and fmt are built-in subcommands. There is no scripts section and no main or bin field: src/main.rs is the default binary and src/lib.rs the library.
One rule catches almost everyone. In package.json, a bare "1.0.11" pins exactly that version. In Cargo.toml, a bare "1.0.140" already means ^1.0.140, any release from 1.0.140 up to but not including 2.0.0, and an exact pin needs "=1.0.11"; cargo metadata reported ^1, ^1.0.140 and =1.0.11 for the manifest below. Dependencies must also be declared to be visible. Node can find an undeclared package in a parent node_modules, but Cargo passes only declared crates to rustc, so an undeclared one is an unresolved import, E0432.
[package]name = "tasks"version = "0.1.0"edition = "2024"
[dependencies]serde = { version = "1", features = ["derive"] } # ^1: any 1.x releaseserde_json = "1.0.140"# ^1.0.140, not an exact pintokio = { version = "1", features = ["macros", "rt-multi-thread", "time"] }
itoa = "=1.0.11"# an exact pin, like npm's "1.0.11"
[dev-dependencies]pretty_assertions = "1"
Build a small Rust CLI that turns task lines into JSON
The last example is the kind of program a Node.js developer would write as a quick script. It reads lines such as 1, Port the config loader, done, validates each into a typed Task and prints JSON with the valid tasks and the rejected lines. It uses only the standard library, so a bare rustc builds it. parse_task borrows each line as &str and returns Result<Task, String>: ? handles a bad id, ok_or turns a missing title into an error, and the status match refuses unknown values instead of defaulting them. The Task owns its title, so to_string() copies it out of the borrowed line.
Without arguments it used the built-in sample and printed one line of JSON, which python3 -m json.tool accepted: two tasks, one with escaped inner quotes, and two rejected lines, line 3 for the id x and line 4 for the status later. With a path argument it reads that file instead. When main returns Err, Rust prints the error's Debug form and exits with status 1; a missing file printed Error: "missing.txt: No such file or directory (os error 2)".
In a real project, Serde derives Serialize and Deserialize for your structs, and serde_json::from_str::<Task> returns a Result, so JSON from outside is checked against the type instead of being asserted with as. That is the Rust answer to JSON.parse(raw) as User; the hand-written json_string only keeps this example free of dependencies.
use std::{env, fs};
#[derive(Debug, PartialEq)]enum Status {
Open,
Done,
}
#[derive(Debug)]struct Task {
id: u32,
title: String,
status: Status,
}
/// Parses `id, title[, open|done]` into a Task, or says what is wrong.fn parse_task(line: &str) -> Result<Task, String> {
letmut fields = line.split(',').map(str::trim);
let id = fields.next().unwrap_or("");
let id: u32 = id.parse().map_err(|e| format!("id {id:?}: {e}"))?;
let title = fields.next().filter(|t| !t.is_empty()).ok_or("missing title")?;
let status = match fields.next() {
None | Some("open") => Status::Open,
Some("done") => Status::Done,
Some(other) => returnErr(format!("unknown status {other:?}")),
};
Ok(Task { id, title: title.to_string(), status })
}
/// A JSON string literal: quotes, backslashes and control characters escaped.fn json_string(text: &str) -> String {
letmut out = String::from("\"");
for c in text.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
c if c.is_control() => out.push_str(&format!("\\u{:04x}", c asu32)),
c => out.push(c),
}
}
out.push('"');
out
}
const SAMPLE: &str = "1, Port the config loader, done
2, Rename \"user_id\"
x, Write tests
3, Measure, later
";
fn main() -> Result<(), String> {
// `tasks todo.txt` reads a file; without an argument the sample is used.let input = match env::args().nth(1) {
Some(path) => fs::read_to_string(&path).map_err(|e| format!("{path}: {e}"))?,
None => SAMPLE.to_string(),
};
let (mut tasks, mut rejected) = (Vec::new(), Vec::new());
for (index, line) in input.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
match parse_task(line) {
Ok(task) => tasks.push(task),
Err(reason) => rejected.push((index + 1, reason)),
}
}
let tasks: Vec<String> = tasks
.iter()
.map(|t| format!(r#"{{"id":{},"title":{},"done":{}}}"#, t.id, json_string(&t.title), t.status == Status::Done))
.collect();
let rejected: Vec<String> = rejected
.iter()
.map(|(line, reason)| format!(r#"{{"line":{line},"error":{}}}"#, json_string(reason)))
.collect();
println!(r#"{{"tasks":[{}],"rejected":[{}]}}"#, tasks.join(","), rejected.join(","));
Ok(())
}
Start small and pure. A parser, a validator, a pricing rule or a CLI is easier to port than an HTTP service, because it has clear inputs and outputs and needs no runtime. First record what the TypeScript does with awkward input: 0, an empty string, a missing field, null, a number above 2^53 and non-ASCII text. Those cases become your first Rust tests, and the differences surface there. Number("") is 0 while "".parse::<u32>() is an error, and "café".length is 4 UTF-16 code units while "café".len() is 5 UTF-8 bytes.
Translate types before functions. Interfaces that hold data become structs, discriminated unions become enums, optional fields become Option<T>, and each number becomes a chosen type such as u32, i64 or f64, with checked arithmetic where overflow is possible. Array method chains become iterator chains, which are lazy. At each function boundary choose &T to read, &mut T to change or a value to consume. Replace throw with Result and an error enum, keep panics for bugs, and parse outside data instead of asserting its type.
Leave async for last: pick a runtime, .await every future you create, use join! where you used Promise.all, spawn only work that must outlive the current function, and treat a timeout as cancellation. Commit Cargo.lock for applications, remember that a bare version is a caret requirement, and run cargo clippy and cargo test before you compare the port with the original.
Practise the bridge course in the Playground or with an AI agent
All 20 lessons are free on the website, and each opens a practice copy in the browser Playground, which compiles Rust on your own device with a real rustc for wasm32-wasip1. In the iPhone and iPad app the bridge courses arrive with Crabrix 1.2, the next app version. The Rust for Node.js Developers learning path continues past the bridge course to 47 lessons: ownership in depth, traits, error design, a CLI and an HTTP API, then async Rust with backpressure and graceful shutdown.
To learn with an AI agent, connect Claude, Claude Code, Codex, Cursor or another MCP client to Crabrix Academy at https://crabrix.com/mcp/academy, which is read-only and needs no sign-in, or run npx -y crabrix@0.6.0 academy locally. The Learn with AI page has a prompt for Node.js developers, and every lesson page has its own. The agent's review of your code is marked AI reviewed: only the checks in the Crabrix app record progress, and the agent cannot change it.