diff --git a/src/apis/audio.ts b/src/apis/audio.ts index 30f3b03..ddd403c 100644 --- a/src/apis/audio.ts +++ b/src/apis/audio.ts @@ -17,7 +17,7 @@ import { SpeechCreateParams } from 'openai/resources/audio/speech'; import { Stream } from '../streaming'; import { AUDIO_FILE_DURATION_HEADER } from '../constants'; import getAudioFileDuration from '../getAudioDuration'; -import { isRunningInBrowser } from '../core'; +import { isFsModuleAvailable } from '../core'; export class Audio extends ApiResource { transcriptions: transcriptions; @@ -78,7 +78,8 @@ export class transcriptions extends ApiResource { > { // @ts-ignore const path = body.file?.path; - if (path && this.client.calculateAudioDuration && !isRunningInBrowser()) { + + if (path && this.client.calculateAudioDuration && isFsModuleAvailable()) { const duration = await getAudioFileDuration(path); if (duration) { params = { @@ -110,7 +111,8 @@ export class translations extends ApiResource { ): Promise { const body: any = _body; const path = body.file?.path; - if (path && this.client.calculateAudioDuration && !isRunningInBrowser()) { + + if (path && this.client.calculateAudioDuration && isFsModuleAvailable()) { const duration = await getAudioFileDuration(path); if (duration) { params = { diff --git a/src/core.ts b/src/core.ts index dd62504..316baec 100644 --- a/src/core.ts +++ b/src/core.ts @@ -59,3 +59,12 @@ export const isRunningInBrowser = () => { typeof navigator !== 'undefined' ); }; + +export const isFsModuleAvailable = () => { + try { + require('fs'); + return true; + } catch (e) { + return false; + } +}; diff --git a/src/getAudioDuration.ts b/src/getAudioDuration.ts index 49d75a6..c75fd29 100644 --- a/src/getAudioDuration.ts +++ b/src/getAudioDuration.ts @@ -1,6 +1,6 @@ -import { isRunningInBrowser } from './core'; +import { isFsModuleAvailable } from './core'; -const isBrowser = isRunningInBrowser(); +const fsAvailable = isFsModuleAvailable(); let fs: any; let open: any; @@ -8,7 +8,8 @@ let read: any; let stat: any; let close: any; -if (!isBrowser) { +// Check if we're in Node.js AND fs module is available +if (fsAvailable) { try { fs = require('fs'); const { promisify } = require('util'); @@ -27,7 +28,8 @@ if (!isBrowser) { * Uses optimized file reading to avoid loading entire files into memory */ async function getAudioFileDuration(filePath: string): Promise { - if (isBrowser || !fs) { + // Only proceed if we're in Node.js, fs is available, and fs module loaded successfully + if (!fsAvailable || !fs) { return null; }