Class MediaUtils

Utility class for media manipulation, including image processing and data URL handling.

Methods

  • Checks if a string is a data URL.

    Parameters

    • dataUrl: string

      The string to check.

    Returns boolean

    True if the string is a data URL, false otherwise.

    import {MediaUtils} from 'nodejs-shared';

    if (MediaUtils.isDataUrl('data:image/jpeg;base64,AA==...'))
    ;
  • Parses a data URL and extracts its components (MIME type, base64 data, file extension, and byte size). Normalizes "jpeg" extension to "jpg".

    Parameters

    • dataUrl: string

      The data URL to parse.

    Returns null | DataUrlParts

    An object containing the parsed type, base64 data, extension, and bytesize, or null if the input is not a valid data URL.

    import {MediaUtils} from 'nodejs-shared';

    // Parse a data URL to extract its MIME type, base64 encoded data, file extension, and size.
    const dataUrlParts = MediaUtils.parseDataUrl('data:image/jpeg;base64,AA==...');
    console.log(dataUrlParts);
    // {
    // mimeType: 'image/jpeg',
    // base64: '/9j/4AAQSk...',
    // extension: 'jpg',
    // bytesize: 45056
    // }
  • Writes image data to a file.

    Parameters

    • outputPath: string

      The path to the output file. The file extension must be provided.

    • data: string | Buffer

      The image data as a data URL, Buffer, or SVG string.

    • options: WriteImageOptions = ...

      File write options.

    Returns void

    import {MediaUtils} from 'nodejs-shared';

    // Write a JPEG image using a data URL.
    MediaUtils.writeImage('path/to/image.jpg', 'data:image/jpeg;base64,AA==...');

    // Write a PNG image using a Buffer.
    MediaUtils.writeImage('path/to/image.png', Buffer.from([...]));

    // Write an SVG image using a string.
    writeImage('path/to/image.svg', '<svg>...</svg>');

    // Write with file system options.
    MediaUtils.writeImage('path/to/image.png', Buffer.from([...]), {mode: 0o644, owner: {username: 'nginx', groupName: 'nginx'}});

    If data is not a string or Buffer, or if the data URL is invalid.

    If the file writing operation fails.