jq-wasm

July 5, 2026 ยท View on GitHub

jq-wasm is a WebAssembly-powered version of the powerful jq JSON processor, built using Emscripten. It brings the versatility of jq to Node.js, modern browsers, and edge runtimes like Cloudflare Workers without any native dependencies.

๐Ÿš€ Features

  • Cross-Platform: One import runs jq in Node.js (ESM + CommonJS), browsers/bundlers, and Cloudflare Workers / Vercel Edge โ€” the right build is auto-selected via package exports.
  • No Native Dependencies: Everything runs in WebAssembly.
  • Fully Typed: Comes with TypeScript definitions for a great developer experience.
  • Familiar jq Syntax: Use standard jq queries and command-line flags.

๐Ÿ“ฆ Installation

Install via npm:

npm install jq-wasm

or with Yarn:

yarn add jq-wasm

๐Ÿ› ๏ธ Usage

Zero-config convenience (async)

For simple, one-off queries, import the top-level async functions directly. A default instance is created and reused automatically.

import { json, first, raw, version } from "jq-wasm";

// json() always returns an array โ€” one element per jq output value
const results = await json({ foo: "bar", list: [1, 2, 3] }, ".list[]");
// โ†’ [1, 2, 3]

const first_result = await first({ a: 1 }, ".a");
// โ†’ 1

// raw() never throws on jq-level errors; inspect exitCode/stderr yourself
const { stdout, stderr, exitCode } = await raw({ x: [1, 2] }, ".x | .[]");

const v = await version();
// โ†’ "jq-1.8.2"

Factory pattern: load once, call synchronously

Use loadJq(options?) when you need synchronous method calls after initialization โ€” ideal for Piscina worker pools, server workers, or anywhere you want to avoid per-call async overhead.

import { loadJq } from "jq-wasm";

const jq = await loadJq(); // async init once

// All handle methods are SYNCHRONOUS
const results = jq.json({ a: [1, 2, 3] }, ".a[]");
// โ†’ [1, 2, 3]

const one = jq.first({ a: 1 }, ".a");
// โ†’ 1

for (const value of jq.stream({ a: [1, 2, 3] }, ".a[]")) {
  use(value); // lazy, sync iteration
}

const { stdout, stderr, exitCode } = jq.raw({ x: 1 }, ".x");

console.log(jq.version); // sync getter โ†’ "jq-1.8.2"

Platform support

The same import works everywhere โ€” the correct build is selected automatically via package.json export conditions:

EnvironmentNotes
Node.js (ESM & CommonJS), BunWorks out of the box; jq.wasm is read from disk.
Vite, webpack, RollupBundler handles the wasm asset (see recipes below).
Cloudflare Workers, Vercel EdgeAuto-selected via workerd / edge-light conditions.
Browsers via CDN / native ESMjq.wasm is fetched alongside the module.
Single-file bundles (jq-wasm/inline)Wasm embedded as bytes โ€” no separate asset to locate.

๐Ÿ“– API

loadJq(options?): Promise<Jq>

Compiles the wasm and returns a ready-to-use synchronous handle. Each call creates an independent instance (useful for worker pools โ€” call loadJq() once per worker, then make synchronous calls per task).

Loader knobs (supply at most one; supplying more than one throws TypeError):

OptionTypeWhen to use
wasmBinaryArrayBuffer | Uint8ArrayYou already have the bytes (e.g. from readFileSync).
wasmURLstring | URLPoint to the asset; loadJq fetches/reads it. Node: http(s):// is fetched, file:///paths are read from disk. Browser: fetched. Edge/inline: unsupported (rejects with guidance).
wasmModuleWebAssembly.ModulePre-compiled module โ€” for Workers / cross-thread transfer.
instantiateWasmfunctionFull Emscripten escape hatch for custom instantiation. Must call onSuccess(instance); the return value is ignored (returning exports without calling back rejects instead of hanging).
(none)โ€”Platform default (Node: disk; browser: fetch; edge: pre-compiled module; inline: embedded bytes).

Handle methods (synchronous)

All methods on the returned Jq handle are synchronous โ€” call them without await.

jq.raw(input, query, flags?): JqResult

Low-level: runs jq and returns { stdout, stderr, exitCode }. Never throws on jq-level errors. Use this when you need full control over the output, or to inspect warnings.

  • input: string | number | boolean | object | null. A string is passed to jq as-is (raw JSON text); all other types are JSON.stringify-d first.
  • query: A jq query string.
  • flags (optional): Array of jq CLI flags (e.g. ["-r"] for raw string output).

jq.json<T>(input, query, flags?): T[]

Runs jq and returns all outputs as an array โ€” [] when jq produces no output. Throws JqError on a real jq failure (see Error model below).

Because json()/first()/stream() parse jq's output as JSON, flags that change the output format (-r/--raw-output, -j/--join-output, --tab, --indent, --seq, -C/--color-output) are rejected with a TypeError โ€” use raw() for non-JSON output.

jq.first<T>(input, query, flags?): T | undefined

Returns the first output value, or undefined if jq produces no output. Throws JqError on failure.

jq.stream<T>(input, query, flags?): IterableIterator<T>

Returns a lazy synchronous iterator over parsed output values. Throws JqError on failure.

jq.version: string

Sync getter. Returns the underlying jq version string (e.g. "jq-1.8.2"), computed on first access and memoized.

Zero-config async functions

These functions use a memoized default handle and are always async. They are equivalent to the handle methods, but do not require an explicit loadJq() call.

raw(input, query, flags?): Promise<JqResult>
json<T>(input, query, flags?): Promise<T[]>
first<T>(input, query, flags?): Promise<T | undefined>
version(): Promise<string>

There is no top-level stream โ€” for streaming, use loadJq() and call jq.stream(...) on the handle.

Error model

json(), first(), and stream() throw a typed JqError under exactly one condition:

exitCode !== 0 and stderr !== ""

jq situationexitCodestderrBehavior
Success0""Return result(s)
Warning (debug, deprecation, @stderr)0non-emptyReturn result(s) โ€” warnings do not throw. Use raw() to inspect them.
Compile / runtime errorโ‰  0non-emptyThrow JqError
--exit-status / -e truthinessโ‰  0""Return result(s) โ€” use raw() to check exitCode.

raw() never throws on jq-level errors.

JqError carries .stderr, .exitCode, and .query. e instanceof JqError is safe even when multiple copies of the package coexist (CJS + ESM, or jq-wasm + jq-wasm/inline): the check matches by error name, not class identity.

Two guard rails around the JSON-parsing methods: output-format flags are rejected up front with a TypeError (see jq.json above), and in the unlikely event jq still emits something unparseable, it surfaces as a JqError โ€” never a bare SyntaxError.

Sub-exports

  • jq-wasm/jq.wasm โ€” resolves to the wasm asset. Feed it to the loader knobs (see Bundler recipes below).
  • jq-wasm/inline โ€” the wasm is embedded as bytes. Exports the same API (loadJq, raw, json, first, version) with no separate asset to locate. Useful for single-file bundles and environments where asset resolution is awkward.

๐Ÿ”ง Bundler / framework recipes

These recipes pair the bundler's asset-resolution side with the correct loadJq knob. They were verified against jqplay.

Node.js / Next.js output: "standalone"

import { loadJq } from "jq-wasm";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";

const require = createRequire(import.meta.url);

const jq = await loadJq({
  wasmBinary: readFileSync(require.resolve("jq-wasm/jq.wasm")),
});

The explicit require.resolve puts jq.wasm in Next's static-analysis import graph, so when this module is part of a traced route, the file tracer copies the wasm into the standalone output automatically โ€” no outputFileTracingIncludes needed. The createRequire line makes the snippet work in plain Node ESM too (in CJS, drop it and use the built-in require).

One caveat for out-of-bundle workers (piscina / worker_threads files loaded from disk at runtime): Next copies outputFileTracingIncludes globs verbatim without tracing through them, so a force-included worker's require() graph never enters the trace. List the worker's jq-wasm closure explicitly:

outputFileTracingIncludes: {
  "/api/your-route": [
    "./src/workers/your-worker.cjs",
    "./node_modules/jq-wasm/package.json",
    "./node_modules/jq-wasm/dist/index.cjs", // ESM worker (.mjs)? dist/index.mjs instead
    "./node_modules/jq-wasm/dist/build/jq.wasm",
  ],
},

Match the entry file to the worker's module system: a CJS worker resolves jq-wasm to dist/index.cjs, an ESM worker to dist/index.mjs (both are self-contained; the jq-wasm/jq.wasm subpath resolves to the same wasm file either way).

webpack (including Web Workers)

Add an asset module rule to your webpack config:

// webpack.config.js
module.exports = {
  module: {
    rules: [
      { test: /jq-wasm[\\/].*\.wasm$/, type: "asset/resource" },
    ],
  },
};

Then import the URL and pass it to loadJq:

import { loadJq } from "jq-wasm";
import wasmUrl from "jq-wasm/jq.wasm";

const jq = await loadJq({ wasmURL: wasmUrl });

This reliably emits the asset across nested-worker chunks where new URL(import.meta.url) does not.

Vite

import { loadJq } from "jq-wasm";
import wasmUrl from "jq-wasm/jq.wasm?url";

const jq = await loadJq({ wasmURL: wasmUrl });

Cloudflare Workers / edge

Zero-config works automatically (the workerd export condition is auto-selected). For explicit control with a pre-compiled module:

import { loadJq } from "jq-wasm";
import mod from "./jq.wasm"; // pre-compiled WebAssembly.Module

const jq = await loadJq({ wasmModule: mod });

No bundler / single-file / esbuild

import { json } from "jq-wasm/inline"; // wasm embedded โ€” no separate asset

const results = await json({ a: 1 }, ".a");

Browser via CDN (no build step)

An import map pointing at esm.run (jsDelivr) is all it takes:

<script type="importmap">
  { "imports": { "jq-wasm": "https://esm.run/jq-wasm@3.0.0-jq-1.8.2" } }
</script>
<script type="module">
  import { json, version } from "jq-wasm";

  console.log(await version());                          // "jq-1.8.2"
  console.log(await json({ a: [1, 2, 3] }, ".a | add")); // [6]
</script>

Or skip the import map and load the browser build directly:

import { json } from "https://cdn.jsdelivr.net/npm/jq-wasm@3.0.0-jq-1.8.2/dist/browser.mjs";
// also works: https://unpkg.com/jq-wasm@3.0.0-jq-1.8.2/dist/browser.mjs
//             https://ga.jspm.io/npm:jq-wasm@3.0.0-jq-1.8.2/dist/browser.mjs

Both forms stream the sibling dist/build/jq.wasm from the same CDN on first use (use an exact version in the URL โ€” CDNs serve raw files per-version). To pin the binary independently or self-host it, pass loadJq({ wasmURL: ".../dist/build/jq.wasm" }).

Verified on jsDelivr (esm.run and raw files), unpkg, and ga.jspm.io. Skypack and dev.jspm.io fail at the CDN side (unmaintained / deprecated in favor of ga.jspm.io).

๐Ÿ”„ Migrating from v2

v3 has two behavioral breaking changes:

1. json() always returns an array

v2v3
json() โ†’ scalar (1 result) / array (N results) / null (0 results)json() โ†’ T[] always ([] when 0 results)

Migration:

// v2: const result = await json(input, ".foo"); // could be scalar or null

// v3 โ€” one result:
const result = await first(input, ".foo");       // โ†’ T | undefined
// or: (await json(input, ".foo"))[0]

// v3 โ€” no result (was null, now []):
const results = await json(input, ".foo");
if (results.length === 0) { /* no output */ }

2. json() no longer throws on benign stderr

v2v3
json() throws if jq writes anything to stderrjson() throws JqError only when exitCode !== 0 AND stderr !== ""

jq warnings (debug, deprecations, @stderr) exit with code 0 and do not throw in v3. If you were catching those warning-throws, check raw().stderr instead.

Smaller behavioral changes

  • Inputs widened: null, numbers, and booleans are now accepted as input (stringified for jq); v2 rejected them with a TypeError. If you relied on that TypeError as a null-input guard, validate before calling.
  • Output-format flags rejected: json()/first()/stream() now throw a TypeError for flags like -r, -j, --tab, --seq (v2 ran them and threw or mis-parsed, depending on the flag). raw() accepts all flags, unchanged.

Unchanged: raw() output contract ({ stdout, stderr, exitCode }, never throws on jq-level errors), async top-level version(), string-input-as-raw-JSON-text semantics, jq-wasm/inline.

๐Ÿ“š License

This project is licensed under the MIT License.

๐ŸŒŸ Contributions

Contributions, issues, and feature requests are welcome! Feel free to check out the issues page.