handbrake-js

repository·master·Indexed 19 days ago

https://github.com/75lb/handbrake-js

A Node.js wrapper for HandbrakeCLI (version 8.0.2) that provides a foundation for building video transcoding software. It allows developers to programmatically convert video files using an event-driven API via hbjs.spawn(), Promises via hbjs.run(), or callbacks via hbjs.exec(). The package includes a command-line application and supports real-time progress monitoring, custom HandbrakeCLI paths, and specific error handling via the eError enum.

Tokens
2.7K
Snippets
9
Records
15
Agent score
68%

What's inside handbrake-js

  1. Configure system requirements and HandbrakeCLI path

    master

    System Requirements

    • Mac and Windows: Only node.js is required; the binary is installed automatically.
    • Linux (Ubuntu): You must install handbrake-cli manually:
      sudo apt install handbrake-cli
    • Other Linux distros: Use flatpak to install the GUI and CLI together.

    Specifying a custom HandbrakeCLI path

    In environments like Docker where the binary might not be in the default location, you can specify the path in two ways:

    1. Environment Variable: Set HANDBRAKECLI_PATH.
      HANDBRAKECLI_PATH="./example/HandbrakeCLI"
    2. Programmatically: Pass HandbrakeCLIPath in the options object to any handbrake-js method.
  2. Install handbrake-js

    master

    You can use handbrake-js either as a library in your Node.js project or as a global command-line application.

    As a library

    Install it as a dependency in your project directory:

    $ npm install handbrake-js --save

    As a command-line app

    Install it globally to use the handbrake command anywhere in your terminal:

    $ npm install -g handbrake-js
  3. Monitor Handbrake process events

    master

    The Handbrake class (returned by hbjs.spawn()) extends EventEmitter and allows you to monitor the lifecycle of a transcoding process. You should attach listeners to these events to track progress, handle errors, or detect completion.

    Emitted Events:

    • start: Fired as HandbrakeCLI is launched.
    • begin: Fired when encoding actually begins.
    • progress: Fired at regular intervals with a progress object containing details like percentComplete, fps, avgFps, eta, and task (e.g., "Encoding" or "Muxing").
    • output: Fired whenever new data is received from stdout or stderr.
    • error: Fired when an operational exception occurs. The error object includes name, message, errno, output, and options.
    • end: Fired on successful completion of an encoding task.
    • complete: Fired when the HandbrakeCLI process exits cleanly.
    • cancelled: Fired if the process was stopped via .cancel().
  4. Use the handbrake-js CLI to encode video

    master

    The handbrake-js CLI allows you to run HandBrake encoding tasks directly from your terminal. When providing both an --input and an --output path, the CLI automatically attaches a progress reporter that displays real-time statistics including task name, percentage complete, current FPS, average FPS, and ETA.

    To see raw output instead of the progress bar, use the --verbose flag.

    # Example usage (assuming cli-options are configured)
    # hbjs --input input.mp4 --output output.mp4
    
    # To see full output instead of the progress bar:
    # hbjs --input input.mp4 --output output.mp4 --verbose
  5. Use hbjs.exec() for short-duration tasks with callbacks

    master

    Use hbjs.exec(options, [onComplete]) to run a HandbrakeCLI command and execute a callback once it finishes. This is best suited for quick tasks where you don't need progress updates.

    Parameters:

    • options: Object containing HandbrakeCLI options.
    • onComplete: A callback function with the signature (err, stdout, stderr).
    import hbjs from 'handbrake-js'
    
    hbjs.exec({ 'preset-list': true }, function(err, stdout, stderr){
      if (err) throw err
      console.log(stdout)
    })
  6. Cancel a running Handbrake process

    master
    If you are using hbjs.spawn(), you can stop the transcoding process by calling the .cancel() method on the returned Handbrake instance. This kills the underlying HandbrakeCLI process and emits a cancelled event.
  7. Use hbjs.run() for short-duration tasks with Promises

    master

    Use hbjs.run(options) to run a HandbrakeCLI command and return a Promise. This is identical to hbjs.exec but uses the Promise pattern instead of callbacks. Use this when you don't need progress events.

    Returns: Promise<{ stdout: string, stderr: string }>

    import hbjs from 'handbrake-js'
    
    async function start () {
      const result = await hbjs.run({ version: true })
      console.log(result.stdout)
      // prints 'HandBrake 1.3.0'
    }
    
    start().catch(console.error)
  8. Use hbjs.spawn() to monitor transcoding progress

    master

    Use hbjs.spawn(options) to start a transcoding process and receive real-time events. This is the best method when you need to track progress or handle long-running tasks.

    Returns: A Handbrake instance (an EventEmitter).

    Available Events:

    • start: Fired when HandbrakeCLI is launched.
    • begin: Fired when encoding actually begins.
    • progress: Fired at intervals with a progress object containing percentComplete, eta, fps, etc.
    • output: Fired with the aggregate stdout and stderr output.
    • error: Fired on operational exceptions.
    • complete: Fired when the process finishes successfully.
    • cancelled: Fired if handbrake.cancel() is called.
    • end: Fired when the process ends.
    import hbjs from 'handbrake-js'
    const options = {
      input: 'something.avi',
      output: 'something.mp4',
      preset: 'Normal',
      rotate: 1
    }
    
    hbjs.spawn(options)
      .on('error', console.error)
      .on('output', console.log)
  9. Handle Handbrake errors with eError

    master

    Errors emitted by the error event contain an error.name property which corresponds to the eError enum. Use these to identify the type of failure:

    • VALIDATION: Input/output path conflicts or missing output paths.
    • INVALID_INPUT: The input file is not a valid video file.
    • INVALID_PRESET: The specified preset is invalid.
    • NOT_FOUND: The HandbrakeCLI binary could not be found.
    • OTHER: Handbrake crashed.
  10. Spawn a Handbrake process with hbjs.spawn()

    master

    Use hbjs.spawn(options) when you need to monitor the transcoding process in real-time. It returns a Handbrake instance which is an EventEmitter, allowing you to listen for progress, output, and error events.

    Options:

    • options: An object containing HandbrakeCLI options.
    • options.HandbrakeCLIPath: (Optional) A string to override the default HandbrakeCLI binary path.

    Returns: A Handbrake instance.

    Available Events on the Handbrake instance:

    • progress: Emitted during the process.
    • output: Emitted when output is available.
    • error: Emitted on error.
    • complete: Emitted when finished successfully.
    • cancelled: Emitted if the process was cancelled.
    • end: Emitted when the process ends.
    import hbjs from 'handbrake-js'
    const options = {
      input: 'something.avi',
      output: 'something.mp4',
      preset: 'Normal',
      rotate: 1
    }
    hbjs.spawn(options)
      .on('error', console.error)
      .on('output', console.log)
  11. Access Handbrake process output and options

    master

    The Handbrake instance provides read-only access to the configuration used and the accumulated output from the CLI.

    • handbrake.output (string): A cumulative string containing all stdout and stderr output produced by the HandbrakeCLI process.
    • handbrake.options (object): A copy of the options object passed to hbjs.spawn() during initialization.
  12. Run Handbrake tasks with hbjs.run()

    master

    Use hbjs.run(options) for simple, asynchronous tasks where you only need the final output and do not require real-time progress events. It returns a Promise that fulfills with an object containing stdout and stderr strings. This is ideal for quick commands like checking the version or listing presets.

    Options:

    • options: An object containing HandbrakeCLI options.
    • options.HandbrakeCLIPath: (Optional) A string to override the default HandbrakeCLI binary path.
    import hbjs from 'handbrake-js'
    async function start () {
      const result = await hbjs.run({ version: true })
      console.log(result.stdout)
      // prints 'HandBrake 1.3.0'
    }
    start().catch(console.error)