> ## Documentation Index
> Fetch the complete documentation index at: /docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Cut clips from a video link by what's said, in Node

> A Node.js script for clipping tools: one Importly job returns the video file and a timestamped transcript, then your app finds every sentence with a phrase and cuts each one into its own MP4 with ffmpeg.

A clipping tool, highlight reel or repurposing app needs two things from a link: the full video file and a transcript with timestamps, so it can find the moment and cut it. Fetching the file yourself means a download tool that gets blocked once it runs on a server, and the timestamps mean a separate speech-to-text step. One Importly import returns both. This script takes a link and a phrase, finds every sentence where it's said, and cuts each one into its own MP4 with ffmpeg on your machine or server. It runs on Node 18 or later with no npm dependencies. The [Python version](/docs/recipes/clips-by-phrase-python.md) does the same with `httpx`.

## The code

```js cut-clips.mjs theme={null}
import { spawnSync } from 'node:child_process'
import { mkdirSync, writeFileSync } from 'node:fs'

const [url, phrase] = process.argv.slice(2)
const PAD = 0.5 // seconds of context before and after each sentence
const API = 'https://api.importly.io'
const headers = {
  Authorization: `Bearer ${process.env.IMPORTLY_API_KEY}`,
  'Content-Type': 'application/json',
}

const fail = (message) => {
  console.error(message)
  process.exit(1)
}

const importWithTranscript = async (link) => {
  const res = await fetch(`${API}/import`, {
    method: 'POST',
    headers,
    body: JSON.stringify({
      url: link,
      videoQuality: '720p',
      compatibleCodecs: true, // H.264 + AAC: plays and edits everywhere
      includeTranscript: true,
      transcriptMode: 'ai', // speech-to-text: sentence-level timestamps
      maxCostDollars: 1.0,
    }),
  })
  const body = await res.json()
  if (!res.ok || !body.success) fail(`Import not started: ${body.code} ${body.error}`)

  const { jobId } = body.data
  while (true) {
    const status = await fetch(`${API}/import/status?id=${jobId}`, { headers })
    const { data } = await status.json()
    if (data.status === 'completed') return data.result
    if (data.status === 'failed') fail(`Import failed: ${data.code} ${data.message}`)
    await new Promise((resolve) => setTimeout(resolve, 5000))
  }
}

const matchingSegments = (transcript, text) => {
  const needle = text.toLowerCase()
  return transcript.data.segments.filter((s) => s.text.toLowerCase().includes(needle))
}

const download = async (mediaUrl, path) => {
  const res = await fetch(mediaUrl)
  if (!res.ok) fail(`Download failed: HTTP ${res.status}`)
  writeFileSync(path, Buffer.from(await res.arrayBuffer()))
}

const cut = (source, start, end, out) => {
  // Re-encode so the clip starts exactly on the sentence, not on the nearest keyframe
  const run = spawnSync('ffmpeg', [
    '-y', '-loglevel', 'error',
    '-ss', Math.max(start - PAD, 0).toFixed(2), '-to', (end + PAD).toFixed(2),
    '-i', source,
    '-c:v', 'libx264', '-preset', 'veryfast', '-c:a', 'aac',
    out,
  ], { stdio: 'inherit' })
  if (run.status !== 0) fail(`ffmpeg failed on ${out}`)
}

const result = await importWithTranscript(url)
const transcript = result.transcript ?? {}
if (transcript.status === 'skipped') fail(`No transcript: ${transcript.reason}`)

const matches = matchingSegments(transcript, phrase)
if (matches.length === 0) fail(`"${phrase}" isn't said in "${result.title}"`)

mkdirSync('clips', { recursive: true })
await download(result.mediaUrl, 'clips/source.mp4')
const slug = phrase.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '')
matches.forEach((seg, i) => {
  const out = `clips/${slug}-${i + 1}.mp4`
  cut('clips/source.mp4', seg.start, seg.end, out)
  console.log(`${out}  ${seg.start.toFixed(1)}-${seg.end.toFixed(1)}s  "${seg.text}"`)
})

console.log(`Cost: $${result.totalCostInDollars}`)
```

```bash theme={null}
# needs ffmpeg: apt install ffmpeg, or brew install ffmpeg
IMPORTLY_API_KEY=your_api_key node cut-clips.mjs "https://www.youtube.com/watch?v=jNQXAC9IVRw" "elephants"
```

Create your key on the [API key page](https://www.importly.io/dashboard/api-key) (it's shown once) and keep it on the server.

Output for that link:

```text theme={null}
clips/elephants-1.mp4  1.4-3.6s  "All right, so here we are, one of the elephants."
Cost: $0.02
```

## How it works

The import does the heavy part. `includeTranscript: true` with `transcriptMode: "ai"` runs speech-to-text on the same job, so the result carries `mediaUrl` (the video) and `transcript.data.segments`: one segment per sentence, with `start` and `end` in seconds. File and transcript are billed together, and `totalCostInDollars` is the total.

`compatibleCodecs: true` asks for H.264 video with AAC audio, which every editor, browser and phone plays. Leave it out and you may get a smaller AV1 or VP9 file at the same resolution.

`maxCostDollars` caps the job. A long video at 720p plus speech-to-text costs more than a short clip, and a job that would go over the cap fails with `MAX_COST_EXCEEDED` before anything is charged.

The cut re-encodes. Copying the stream (`-c copy`) is faster but starts on the nearest keyframe, which can be seconds before the sentence begins. Re-encoding a short clip takes a moment and lands on the sentence. `PAD` adds half a second on each side so the first and last words aren't clipped.

`matchingSegments` is a plain substring search. Replace it with whatever your app needs: a keyword list, a search index over the segments, or an LLM that reads the transcript and returns the timestamps of the best moments.

`download` reads the whole file into memory, which is fine for short videos. For long ones, stream it to disk instead: `await pipeline(Readable.fromWeb(res.body), createWriteStream(path))` with `pipeline` from `node:stream/promises`.

## Errors to handle

| Where | What you see | What to do |
| - | - | - |
| Start request | HTTP `402` `INSUFFICIENT_BALANCE` | Add credits; nothing was charged. Or set `fitQualityToBalance: true` to fall back to a lower quality |
| Start request | HTTP `429` `RATE_LIMITED` | Wait `retryAfter` seconds. See [Rate limits](/docs/error-handling.md#rate-limits) |
| Status | `status: "failed"`, `code: "VIDEO_UNAVAILABLE"` | The video is gone, private or region-locked. Show the user the message |
| Status | `status: "failed"`, `code: "MAX_COST_EXCEEDED"` | The video is longer than your cap allows. Raise `maxCostDollars` or lower `videoQuality` |
| Result | `transcript.status: "skipped"` | The file arrived but there's no transcript; `transcript.reason` says why |
| Download | An error on `mediaUrl` after a week | The link expires after 7 days. Store the file in your own bucket if you need it longer |

Every error has a `documentationUrl` with the fix. See [Error handling](/docs/error-handling.md).

## In production

Don't poll inside a web request. Start the import from your API route with a `webhookUrl`, and cut the clips in a background worker when Importly calls back. See [Webhooks](/docs/webhooks.md), and [BullMQ](/docs/integrations/bullmq.md) or [Inngest](/docs/integrations/inngest.md) for the worker side.

Keep the source video. Add `store: true` and a `storagePath` so the file also lands in your own bucket, then cut new clips from there whenever a user asks, without importing again. See [Save to your bucket](/docs/integrations/save-to-bucket.md).

Captions cost less when the video has them. Send `transcriptMode: "captions"` (or `"auto"`, the default, which uses captions and falls back to speech-to-text when there are none) and `transcriptLanguage` to use the platform's captions, which are timed line by line and sometimes auto-generated. See [Transcripts](/docs/features/transcripts.md).

> [!NOTE]
>
> A 10-minute 720p video (about 77 MB) costs about $0.15 to import, and $0.10 more for the speech-to-text transcript. Status checks are free. Try it free, no card required. See [Pricing & credits](/docs/billing.md).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.