npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

camera-torch

v0.1.0

Published

Torch, zoom, focus and exposure control for a live web camera stream. No Cordova, no Capacitor - just the browser's own MediaStreamTrack API, done right.

Readme

camera-torch

Turn the phone's flashlight on from a web page. Plus zoom, focus and exposure — on the camera stream you already have.

npm version minzipped size license MIT TypeScript GitHub

Every other torch package on npm is Cordova, Capacitor or React Native. The browser has been able to do this on its own for years — it is just that nothing about the API tells you how.

// Before — looks reasonable, does nothing at all
await track.applyConstraints({ torch: true });               // silently ignored
await navigator.mediaDevices.getUserMedia({ video: { torch: true } }); // throws

// After
const cam = attach(stream);
if (cam.can.torch) await cam.torch(true);                    // the LED comes on

Why this exists

Torch control is four lines of platform API with five ways to get it wrong. This package is those five things:

  • Torch only listens inside the advanced array. applyConstraints({ torch: true }) resolves successfully and does nothing — torch is not a standard constraint, so the basic constraint set is allowed to drop it on the floor. It has to be applyConstraints({ advanced: [{ torch: true }] }), and it can never be part of the original getUserMedia() call (that throws TypeError). This is the number-one reason people conclude the web cannot do torch.
  • getCapabilities() does not always exist. It is absent in Firefox and in a fair number of older Android WebViews, and on some devices it exists but returns {} until the camera has settled. readCapabilities() always hands back a fully-formed object with everything absent, so you branch on data instead of on typeof.
  • The torch survives the track. Stop a track with torch: true still applied and the LED stays physically lit on many Android devices until something else claims the camera — including after the page is closed. detach() writes torch: false before letting go, and the ended event is watched so state never lies. See Gotchas; this is the bug your users will report.
  • Torch needs a live, environment-facing track. A stopped track, an audio track, or a front camera each fail differently and unhelpfully. Here they are 'not-live', 'not-video' and 'unsupported-capability' before anything reaches the device.
  • Zoom has a device-specific range and a step. Ask for zoom: 3 on a camera that reports { min: 1, max: 2.4, step: 0.1 } and you get an OverconstrainedError. zoom() clamps into the real range, snaps to the real step grid (measured from min, not from zero), and resolves with the value it actually applied.
  • OverconstrainedError knows which constraint it rejected — in err.constraint — and nobody ever reads it. Here it becomes a CameraError with code: 'out-of-range' and that constraint name attached.

Install

npm install camera-torch

Or straight from a CDN — the IIFE build exposes the global CameraTorch:

<script src="https://unpkg.com/camera-torch"></script>
<script>
  const cam = CameraTorch.attach(stream);
  if (cam.can.torch) cam.torch(true);
</script>

No runtime dependencies. React is an optional peer dependency, used only by camera-torch/react.

Quick start

import { attach, isSupported } from 'camera-torch';

if (!isSupported()) {
  // Firefox, or an insecure origin. Render your scanner without a torch button.
}

const stream = await navigator.mediaDevices.getUserMedia({
  video: { facingMode: 'environment' },   // the front camera never has a torch
});
document.querySelector('video').srcObject = stream;

const cam = attach(stream);

console.log(cam.can);      // { torch: true, zoom: true, focus: true, exposure: false }
console.log(cam.ranges);   // { zoom: { min: 1, max: 8, step: 0.1 } }

const button = document.querySelector('#torch');
button.hidden = !cam.can.torch;
button.onclick = async () => {
  const on = await cam.toggleTorch();
  button.textContent = on ? 'Torch off' : 'Torch on';
};

// When you are done — this order matters.
cam.detach();                                  // torch off first
stream.getTracks().forEach((t) => t.stop());   // then release the camera

attach() also takes a bare MediaStreamTrack, and attaching twice to the same track hands back the same control object, so it is safe to call from a re-render.

React

import { useCameraTorch } from 'camera-torch/react';

function Scanner({ stream }) {
  const { can, ranges, torchOn, toggleTorch, zoom, error } = useCameraTorch(stream);

  return (
    <>
      {can.torch && (
        <button onClick={() => toggleTorch().catch(() => {})}>
          {torchOn ? 'Torch off' : 'Torch on'}
        </button>
      )}

      {ranges.zoom && (
        <input
          type="range"
          min={ranges.zoom.min}
          max={ranges.zoom.max}
          step={ranges.zoom.step || 0.1}
          defaultValue={ranges.zoom.min}
          onChange={(e) => zoom(Number(e.target.value)).catch(() => {})}
        />
      )}

      {error && <p role="alert">{error.message}</p>}
    </>
  );
}

The hook re-attaches when source changes and detaches on unmount — and because detaching turns the torch off, unmounting the component cannot leave the LED lit. Pass null while you have no stream yet. It is SSR-safe: nothing touches the camera during render.

API

Functions

| Function | Signature | Description | | --- | --- | --- | | isSupported | () => boolean | Whether this browser can control a camera at all. false in Node/SSR, false in Firefox, false without getUserMedia. | | attach | (source: MediaStreamTrack \| MediaStream) => CameraControl | Take control of a video track. A MediaStream resolves to its first video track. | | readCapabilities | (track: TrackLike) => Capabilities | Pure, never throws. Normalises track.getCapabilities(), including when it does not exist. | | clamp | (value: number, range: Range) => number | Pure. Clamps into [min, max] and snaps to the step grid measured from min. |

A default export object holds all four plus CameraError, so import CameraTorch from 'camera-torch' and the IIFE global read the same.

CameraControl

| Member | Type | Description | | --- | --- | --- | | can | { torch, zoom, focus, exposure: boolean } | What this camera can do. Re-read from the track on every access, so late-arriving capabilities are picked up. | | ranges | { zoom?: Range; exposure?: Range } | The device's real ranges. Only present for capabilities it has. | | focusModes | string[] | e.g. ['continuous', 'manual', 'single-shot']. | | torchOn | boolean | Whether this control believes the torch is lit. | | torch(on) | Promise<void> | Switch the torch on or off. | | toggleTorch() | Promise<boolean> | Flip it; resolves with the new state. | | zoom(level) | Promise<number> | Clamped and snapped; resolves with the value actually applied. | | focusMode(mode) | Promise<void> | Rejects if the device does not list that mode. | | exposure(value) | Promise<number> | Clamped and snapped; resolves with the value applied. | | settings() | Record<string, unknown> | track.getSettings(), or {} where it does not exist. | | reset() | Promise<void> | Torch off, zoom to minimum, focus to continuous. Skips capabilities the device lacks. | | detach() | void | Turn the torch off, drop the ended listener, release the control. |

Capabilities

| Field | Type | Description | | --- | --- | --- | | supported | boolean | getCapabilities() existed and returned an object. | | torch | boolean | Device has a web-controllable flash LED. | | zoom | Range \| null | Zoom range. | | focus / focusModes | boolean / string[] | Focus modes the device accepts. | | exposure | Range \| null | Exposure range. | | exposureKey | 'exposureCompensation' \| 'exposureTime' \| null | Which constraint exposure() writes. Not interchangeable — see Gotchas. | | exposureModes | string[] | e.g. ['continuous', 'manual']. | | raw | Record<string, unknown> | The untouched capabilities object, for anything not modelled here. |

Range is { min: number; max: number; step: number }. A step of 0 means the device reported none — treat it as "any value in range".

CameraError

Every rejection is a CameraError with a code, the original error on cause, and (for constraint failures) the blamed constraint.

| code | When | | --- | --- | | 'unsupported' | Nothing track-shaped was passed to attach(). This is what SSR hits. | | 'not-video' | An audio track, or a MediaStream with no video track. | | 'not-live' | The track is stopped/ended, or the control was detached. | | 'unsupported-capability' | The device reports no such capability; the write would be a silent no-op. | | 'out-of-range' | The platform threw OverconstrainedError. err.constraint names the culprit. | | 'apply-failed' | Anything else applyConstraints() threw, kept on err.cause. |

Exported types

Range, Capabilities, CameraControl, CameraAbilities, CameraRanges, CameraError, CameraErrorCode, CameraErrorOptions, ExposureKey, TrackLike, StreamLike, and from camera-torch/react, CameraSource and UseCameraTorch.

Browser support

| Browser | Torch | Zoom / focus / exposure | Notes | | --- | --- | --- | --- | | Chrome / Edge for Android | Yes, rear camera | Yes, where the device reports a range | The main target. Needs HTTPS or localhost. | | Chrome / Edge desktop | Only if the webcam has an LED — almost none do | Rare | can.torch is false; hide the button. | | Samsung Internet | Yes | Yes | Chromium-based. | | Safari, iOS and macOS | No | No | WebKit implements neither the torch constraint nor getCapabilities() for these. isSupported() is false. There is no workaround; an iOS torch needs a native app. | | Firefox, all platforms | No | No | No MediaStreamTrack.getCapabilities(). isSupported() is false, readCapabilities() returns everything absent. | | Node / SSR | n/a | n/a | Importing is safe, isSupported() is false, attach() throws CameraError('unsupported'). |

When it does not work, it does not work loudly: isSupported() tells you before you render a button, can.torch tells you per-device, and every setter rejects with a code instead of quietly doing nothing.

Recipes

QR scanner with a torch button that only appears when it can work

const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
const cam = attach(stream);

torchButton.hidden = !cam.can.torch;
torchButton.onclick = () => cam.toggleTorch().catch((err) => toast(err.message));

// Killing the scanner must not kill the battery.
window.addEventListener('pagehide', () => {
  cam.detach();
  stream.getTracks().forEach((t) => t.stop());
});

Document capture: pin the focus, then zoom in on the page

const cam = attach(stream);

if (cam.focusModes.includes('continuous')) await cam.focusMode('continuous');

// Ask for 3x; find out what you got. On a camera that maxes at 2.4x this returns 2.4.
const applied = await cam.zoom(3);
zoomLabel.textContent = `${applied}x`;

Auto-torch in a dark room, without a torch-less device throwing

async function lightIfNeeded(cam, luminance) {
  if (!cam.can.torch) return false;
  try {
    await cam.torch(luminance < 0.15);
    return cam.torchOn;
  } catch (err) {
    if (err.code === 'not-live') return false;  // camera went away mid-scan
    throw err;
  }
}

Gotchas

  • The LED outlives your page. This is the real bug. track.stop() does not clear a torch that is still applied on many Android devices — the light stays on until another app opens the camera. Always detach() (or torch(false)) before stopping the track. detach() is synchronous and fires the off-write without waiting for it; if you need certainty that it landed, await cam.torch(false) yourself first.
  • The front camera has no torch. Ask for facingMode: 'environment'. On a device with several rear cameras, the torch belongs to whichever physical camera the track opened — you cannot light the wide lens from the telephoto track.
  • Some devices need a frame before they admit to anything. getCapabilities() can return {} for the first few hundred milliseconds. can and ranges re-read on every access, so re-check after the video's loadedmetadata event rather than caching the first answer. The React hook already re-reads once the camera has settled.
  • exposureCompensation and exposureTime are not the same thing. The first is an EV offset around the automatic exposure; the second is a shutter duration in 100µs units that is ignored unless exposureMode is 'manual'. exposure() writes whichever the device reported — capabilities.exposureKey tells you which — and pairs exposureTime with exposureMode: 'manual' in the same advanced entry.
  • Zoom here is the digital zoom of one camera, not a lens switch. It crops; it does not improve detail. It also does not exist on the vast majority of webcams.
  • Two callers, one track. attach() returns one shared control per track, so detach() in one component detaches it for all of them. If two parts of your app need the torch, share the control rather than attaching twice and tearing down independently.
  • HTTPS or nothing. getUserMedia() needs a secure context. localhost counts; a LAN IP over plain HTTP does not.

Contributing

git clone https://github.com/vishalmeena2211/camera-torch.git
cd camera-torch
npm install
npm run dev      # tsup --watch
npm test         # builds, then runs node:test against dist/

demo/index.html is both the demo and the end-to-end test: serve the package root over any local static server, open it, and every automated check reports itself on the page. Anything that needs a real camera is a labelled button and an honest skip, never a fake pass.

Links

License

MIT © Vishal Meena