{"templateId":"markdown","sharedDataIds":{"sidebar":"sidebar-sidebars.yaml"},"props":{"metadata":{"markdoc":{"tagList":["admonition","partial"]},"type":"markdown"},"seo":{"title":"Code Samples","llmstxt":{"hide":false,"sections":[{"title":"Table of contents","includeFiles":["**/*"],"excludeFiles":[]}],"excludeFiles":[]}},"dynamicMarkdocComponents":[],"compilationErrors":[],"ast":{"$$mdtype":"Tag","name":"article","attributes":{},"children":[{"$$mdtype":"Tag","name":"Heading","attributes":{"level":1,"id":"code-samples","__idx":0},"children":["Code Samples"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Use the code samples below to quickly get started developing with the SDK."]},{"$$mdtype":"Tag","name":"Admonition","attributes":{"type":"info"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["These examples require the ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"/sdk/node"},"children":["Rev AI Node SDK"]},"."]}]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"submit-a-local-file-for-transcription","__idx":1},"children":["Submit a local file for transcription"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example demonstrates how to submit a local audio file for transcription."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<FILEPATH>"]}," placeholder with the path to the file you wish to transcribe and the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI account's access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"// create a client\nimport { RevAiApiClient } from 'revai-node-sdk';\n\nvar accessToken = '<REVAI_ACCESS_TOKEN>';\nvar filePath = '<FILEPATH>';\n\n// initialize the client with your access token\nvar client = new RevAiApiClient(accessToken);\n\n// submit a local file\nvar job = await client.submitJobLocalFile(filePath);\n\n// retrieve transcript\n// as plain text\nvar transcriptText = await client.getTranscriptText(job.id);\n\n// or as an object\nvar transcriptObject = await client.getTranscriptObject(job.id);\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"submit-a-remote-file-for-transcription","__idx":2},"children":["Submit a remote file for transcription"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example demonstrates how to submit a remote audio file for transcription."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<URL>"]}," placeholder with the public URL to the file you wish to transcribe and the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI account's access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"import { RevAiApiClient } from 'revai-node-sdk';\n\nvar accessToken = '<REVAI_ACCESS_TOKEN>';\nvar sourceConfig = {url: '<URL>', auth_headers: null};\nconst jobOptions = {source_config: sourceConfig}\n\n// initialize the client with your access token\nvar client = new RevAiApiClient(accessToken);\n\n// submit via a public URL\nvar job = await client.submitJob(jobOptions);\n\n// retrieve transcript\n// as plain text\nvar transcriptText = await client.getTranscriptText(job.id);\n\n// or as an object\nvar transcriptObject = await client.getTranscriptObject(job.id);\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"submit-an-audio-stream-for-transcription","__idx":3},"children":["Submit an audio stream for transcription"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example demonstrates how to submit an audio stream for transcription."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<FILEPATH>"]}," placeholder with the path to the file you wish to transcribe and the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI account's access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"import { RevAiApiClient } from 'revai-node-sdk';\n\nvar accessToken = '<REVAI_ACCESS_TOKEN>';\nvar filePath = '<FILEPATH>';\n\n// initialize the client with your access token\nvar client = new RevAiApiClient(accessToken);\n\n// submit as audio data, the filename is optional\nconst stream = fs.createReadStream(filePath);\nvar job = await client.submitJobAudioData(stream, 'file.mp3');\n\n// retrieve transcript\n// as plain text\nvar transcriptText = await client.getTranscriptText(job.id);\n\n// or as an object\nvar transcriptObject = await client.getTranscriptObject(job.id);\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"stream-a-local-file","__idx":4},"children":["Stream a local file"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example can be used to configure a streaming client, stream audio from a file, and obtain the transcript as the audio is processed."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<FILEPATH>"]}," placeholder with the path to the file you wish to transcribe and the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI account's access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"const revai = require('revai-node-sdk');\nconst fs = require('fs');\n\nconst token = '<REVAI_ACCESS_TOKEN>';\nconst filePath = '<FILEPATH>';\n\n// Initialize your client with your audio configuration and access token\nconst audioConfig = new revai.AudioConfig(\n    /* contentType */ \"audio/x-raw\",\n    /* layout */      \"interleaved\",\n    /* sample rate */ 16000,\n    /* format */      \"S16LE\",\n    /* channels */    1\n);\n\nvar client = new revai.RevAiStreamingClient(token, audioConfig);\n\n// Create your event responses\nclient.on('close', (code, reason) => {\n    console.log(`Connection closed, ${code}: ${reason}`);\n});\nclient.on('httpResponse', code => {\n    console.log(`Streaming client received http response with code: ${code}`);\n})\nclient.on('connectFailed', error => {\n    console.log(`Connection failed with error: ${error}`);\n})\nclient.on('connect', connectionMessage => {\n    console.log(`Connected with message: ${connectionMessage}`);\n})\n\n// Begin streaming session\nvar stream = client.start();\n\n// Read file from disk\nvar file = fs.createReadStream(filePath);\n\nstream.on('data', data => {\n    console.log(data);\n});\nstream.on('end', function () {\n    console.log(\"End of Stream\");\n});\n\nfile.on('end', () => {\n    client.end();\n});\n\n// Stream the file\nfile.pipe(stream);\n\n// Forcibly ends the streaming session\n// stream.end();\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"stream-and-transcribe-microphone-audio","__idx":5},"children":["Stream and transcribe microphone audio"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example can be used to configure your streaming client, send audio as a stream from your microphone input, and obtain the transcript as it is processed."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"const revai = require('revai-node-sdk');\nconst mic = require('mic');\n\nconst token = '<REVAI_ACCESS_TOKEN>';\n\n// initialize client with audio configuration and access token\nconst audioConfig = new revai.AudioConfig(\n    /* contentType */ \"audio/x-raw\",\n    /* layout */      \"interleaved\",\n    /* sample rate */ 16000,\n    /* format */      \"S16LE\",\n    /* channels */    1\n);\n\n// initialize microphone configuration\n// note: microphone device id differs\n// from system to system and can be obtained with\n// arecord --list-devices and arecord --list-pcms\nconst micConfig = {\n    /* sample rate */ rate: 16000,\n    /* channels */    channels: 1,\n    /* device id */   device: 'hw:0,0'\n};\n\nvar client = new revai.RevAiStreamingClient(token, audioConfig);\n\nvar micInstance = mic(micConfig);\n\n// create microphone stream\nvar micStream = micInstance.getAudioStream();\n\n// create event responses\nclient.on('close', (code, reason) => {\n    console.log(`Connection closed, ${code}: ${reason}`);\n});\nclient.on('httpResponse', code => {\n    console.log(`Streaming client received http response with code: ${code}`);\n});\nclient.on('connectFailed', error => {\n    console.log(`Connection failed with error: ${error}`);\n});\nclient.on('connect', connectionMessage => {\n    console.log(`Connected with message: ${connectionMessage}`);\n});\nmicStream.on('error', error => {\n  console.log(`Microphone input stream error: ${error}`);\n});\n\n// begin streaming session\nvar stream = client.start();\n\n// create event responses\nstream.on('data', data => {\n  console.log(data);\n});\nstream.on('end', function () {\n  console.log(\"End of Stream\");\n});\n\n// pipe the microphone audio to Rev AI client\nmicStream.pipe(stream);\n\n// start the microphone\nmicInstance.start();\n\n// Forcibly ends the streaming session\n// stream.end();\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"recover-from-connection-errors-and-timeouts-during-a-stream","__idx":6},"children":["Recover from connection errors and timeouts during a stream"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example can be used to configure a streaming client to transcribe a long-duration stream using a RAW-format audio file. It handles reconnects (whether due to session length timeouts or other connectivity interruption) without losing audio. It also re-aligns timestamp offsets to the new streaming session when reconnecting."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<FILEPATH>"]}," placeholder with the path to the audio file (RAW format) you wish to stream and the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI account's access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"const fs = require('fs');\nconst revai = require('revai-node-sdk');\nconst { Writable } = require('stream');\n\nconst token = '<REVAI_ACCESS_TOKEN>';\nconst filePath = '<FILEPATH>';\nconst bytesPerSample = 2;\nconst samplesPerSecond = 16000;\nconst chunkSize = 8000;\n\n// initialize client with audio configuration and access token\nconst audioConfig = new revai.AudioConfig(\n    /* contentType */ 'audio/x-raw',\n    /* layout */      'interleaved',\n    /* sample rate */ samplesPerSecond,\n    /* format */      'S16LE',\n    /* channels */    1\n);\n\n// optional config to be provided.\nconst sessionConfig = new revai.SessionConfig(\n    metadata='example metadata', /* (optional) metadata */\n    customVocabularyID=null,  /* (optional) custom_vocabulary_id */\n    filterProfanity=false,    /* (optional) filter_profanity */\n    removeDisfluencies=false, /* (optional) remove_disfluencies */\n    deleteAfterSeconds=0,     /* (optional) delete_after_seconds */\n    startTs=0,                /* (optional) start_ts */\n    transcriber='machine',    /* (optional) transcriber */\n    detailedPartials=false,   /* (optional) detailed_partials */\n    language=\"en\"             /* (optional) language */\n);\n\n// begin streaming session\nlet client = null;\nlet revaiStream = null;\n\nlet audioBackup = [];\nlet audioBackupCopy = [];\nlet newStream = true;\nlet lastResultEndTsReceived = 0.0;\n\nfunction handleData(data) {\n    switch (data.type){\n        case 'connected':\n            console.log(\"Received connected\");\n            break;\n        case 'partial':\n            console.log(`Partial: ${data.elements.map(x => x.value).join(' ')}`);\n            break;\n        case 'final':\n            console.log(`Final: ${data.elements.map(x => x.value).join('')}`);\n            const textElements = data.elements.filter(x => x.type === \"text\");\n            lastResultEndTsReceived = textElements[textElements.length - 1].end_ts;\n            console.log(lastResultEndTsReceived * samplesPerSecond * bytesPerSample / 1024);\n            break;\n        default:\n            // all messages from the API are expected to be one of the previous types\n            console.error('Received unexpected message');\n            break;\n    }\n}\n\nfunction startStream() {\n    client = new revai.RevAiStreamingClient(token, audioConfig);\n\n    // create event responses\n    client.on('close', (code, reason) => {\n        console.log(`Connection closed, ${code}: ${reason}`);\n        if (code !== 1000 || reason == 'Reached max session lifetime'){\n            console.log('Restarting stream');\n            restartStream();\n        }\n        console.log(bytesWritten);\n    });\n    client.on('httpResponse', code => {\n        console.log(`Streaming client received HTTP response with code: ${code}`);\n    });\n    client.on('connectFailed', error => {\n        console.log(`Connection failed with error: ${error}`);\n    });\n    client.on('connect', connectionMessage => {\n        console.log(`Connected with job ID: ${connectionMessage.id}`);\n    });\n\n    audioBackup = [];\n    sessionConfig.startTs = lastResultEndTsReceived;\n\n    revaiStream = client.start(sessionConfig);\n    revaiStream.on('data', data => {\n        handleData(data);\n    });\n    revaiStream.on('end', function () {\n        console.log('End of stream');\n    });\n}\n\nlet bytesWritten = 0;\n\nconst audioInputStreamTransform = new Writable({\n    write(chunk, encoding, next) {\n        if (newStream && audioBackupCopy.length !== 0) {\n            // approximate math to calculate time of chunks\n            const bitsSent = lastResultEndTsReceived * samplesPerSecond * bytesPerSample;\n            const chunksSent = Math.floor(bitsSent / chunkSize);\n            if (chunksSent !== 0) {\n                for (let i = chunksSent; i < audioBackupCopy.length; i++) {\n                    revaiStream.write(audioBackupCopy[i][0], audioBackupCopy[i][1]);\n                }\n            }\n            newStream = false;\n        }\n\n        audioBackup.push([chunk, encoding]);\n\n        if (revaiStream) {\n            revaiStream.write(chunk, encoding);\n            bytesWritten += chunk.length;\n        }\n\n        next();\n    },\n\n    final() {\n        if (client && revaiStream) {\n            client.end();\n            revaiStream.end();\n        }\n    }\n});\n\nfunction restartStream() {\n    if (revaiStream) {\n        client.end();\n        revaiStream.end();\n        revaiStream.removeListener('data', handleData);\n        revaiStream = null;\n    }\n\n    audioBackupCopy = [];\n    audioBackupCopy = audioBackup;\n\n    newStream = true;\n\n    startStream();\n}\n\n// read file from disk\nlet file = fs.createReadStream(filePath);\n\nstartStream();\n\nfile.on('end', () => {\n    chunkInputTransform.end();\n})\n\n// array for data left over from chunking writes into chunks of 8000\nlet leftOverData = null;\n\nconst chunkInputTransform = new Writable({\n    write(chunk, encoding, next) {\n        if (encoding !== 'buffer'){\n            console.log(`${encoding} is not buffer, writing directly`);\n            audioInputStreamTransform.write(chunk, encoding);\n        }\n        else {\n            let position = 0;\n\n            if (leftOverData != null) {\n                let audioChunk = Buffer.alloc(chunkSize);\n                const copiedAmount = leftOverData.length;\n                console.log(`${copiedAmount} left over, writing with next chunk`);\n                leftOverData.copy(audioChunk);\n                leftOverData = null;\n                chunk.copy(audioChunk, chunkSize - copiedAmount);\n                position += chunkSize - copiedAmount;\n                audioInputStreamTransform.write(audioChunk, encoding);\n            }\n\n            while(chunk.length - position > chunkSize) {\n                console.log(`${chunk.length - position} bytes left in chunk, writing with next audioChunk`);\n                let audioChunk = Buffer.alloc(chunkSize);\n                chunk.copy(audioChunk, 0, position, position+chunkSize);\n                position += chunkSize;\n                audioInputStreamTransform.write(audioChunk, encoding);\n            }\n\n            if (chunk.length > 0) {\n                leftOverData = Buffer.alloc(chunk.length - position);\n                chunk.copy(leftOverData, 0, position);\n            }\n        }\n\n        next();\n    },\n\n    final() {\n        if (leftOverData != null) {\n            audioInputStreamTransform.write(leftOverData);\n            audioInputStreamTransform.end();\n        }\n    }\n})\n\n// stream the file\nfile.pipe(chunkInputTransform);\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"send-email-notifications-using-a-webhook","__idx":7},"children":["Send email notifications using a webhook"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example demonstrates how to implement a webhook handler that receives and parses the HTTP POST message from the Rev AI API and sends an email notification using Express and the Twilio SendGrid API client."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, you must first replace three placeholders:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<SENDER_EMAIL_ADDRESS>"]}," and ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<RECIPIENT_EMAIL_ADDRESS>"]}," for the sender and recipient email addresses; and"]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":[{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<SENDGRID_API_KEY>"]}," for the Twilio SendGrid API key."]}]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"const bodyParser = require('body-parser');\nconst express = require('express');\nconst sendgrid = require('@sendgrid/mail');\n\n// Twilio SendGrid API key\nconst sendgridKey = '<SENDGRID_API_KEY>';\n// sender email address\nconst senderEmail = '<SENDER_EMAIL>';\n// recipient email address\nconst receiverEmail = '<RECEIVER_EMAIL>';\n\n// set API key for SendGrid\nsendgrid.setApiKey(sendgridKey);\n\n// create Express application\nconst app = express();\napp.use(bodyParser.json());\n\n// handle requests to webhook endpoint\napp.post('/hook', async req => {\n  const job = req.body.job;\n  console.log(`Received status for job id ${job.id}: ${job.status}`);    \n\n  const message = {\n    from: senderEmail,\n    to: receiverEmail,\n    subject: `Job ${job.id} is COMPLETE`,\n    text: job.status === 'transcribed'\n        ? `Log in at https://rev.ai/jobs/speech-to-text/ to collect your transcript.`\n        : `An error occurred. Log in at https://rev.ai/jobs/speech-to-text/ to view details.`\n  };\n\n  try {\n    await sendgrid.send(message);\n    console.log('Email successfully sent');\n  } catch (e) {\n    console.error(e);\n  }\n\n});\n\n//  start application on port 3000\napp.listen(3000, () => {\n  console.log('Webhook listening');\n})\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"save-transcripts-to-mongodb-using-a-webhook","__idx":8},"children":["Save transcripts to MongoDB using a webhook"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example demonstrates how to implement a webhook handler that receives and parses the HTTP POST message from the Rev AI API and then makes a subsequent request to the API to retrieve the complete transcript. The handler then saves the received data to a MongoDB database collection as a JSON document."]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, you must replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<MONGODB_CONNECTION_URI>"]}," with the ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"https://www.mongodb.com/docs/manual/reference/connection-string/"},"children":["connection URI"]}," to your MongoDB database and the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI account's access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"const { RevAiApiClient } = require('revai-node-sdk');\nconst { MongoClient } = require('mongodb');\nconst bodyParser = require('body-parser');\nconst express = require('express');\n\n// MongoDB connection string\nconst mongodbUri = '<MONGODB_CONNECTION_URI>';\n\n// Rev AI access token\nconst revAiToken = '<REVAI_ACCESS_TOKEN>';\n\n// create Express application\nconst app = express();\napp.use(bodyParser.json());\n\n// create Mongo client\nconst mongo = new MongoClient(mongodbUri);\nmongo.connect();\nconst db = mongo.db('mydb');\nconst transcripts = db.collection('transcripts')\n\n// create Rev AI API client\nconst revAiClient = new RevAiApiClient(revAiToken);\n\n// handle requests to webhook endpoint\napp.post('/hook', async req => {\n  const job = req.body.job;\n  console.log(`Received status for job id ${job.id}: ${job.status}`);\n\n  if (job.status === 'transcribed') {\n    // request transcript\n    const transcript = await revAiClient.getTranscriptObject(job.id);\n    console.log(`Received transcript for job id ${job.id}`);\n\n    // create MongoDB document\n    const doc = {\n      job_id: job.id,\n      created_on: job.created_on,\n      language: job.language,\n      status: job.status,\n      transcript\n    }\n\n    // save document to MongoDB\n    try {\n      const result = await collection.insertOne(doc);\n      console.log(`Saved transcript with document id: ${result.insertedId}`);\n    } catch (e) {\n      console.error(e);\n    }\n  }\n});\n\n//  start application on port 3000\napp.listen(3000, () => {\n  console.log('Webhook listening');\n})\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Heading","attributes":{"level":2,"id":"identify-language-for-transcription-using-a-webhook","__idx":9},"children":["Identify language for transcription using a webhook"]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["The following example demonstrates a webhook handler that receives both language identification and transcription job results from the respective APIs. If the results are successful, it performs the following additional processing:"]},{"$$mdtype":"Tag","name":"ul","attributes":{},"children":[{"$$mdtype":"Tag","name":"li","attributes":{},"children":["For language identification jobs, it obtains the list of identified languages and the most probable language, and then initiates an asynchronous transcription request that includes this language information."]},{"$$mdtype":"Tag","name":"li","attributes":{},"children":["For asynchronous transcription jobs, it obtains the final transcript and prints it to the console."]}]},{"$$mdtype":"Tag","name":"p","attributes":{},"children":["To use this example, replace the ",{"$$mdtype":"Tag","name":"code","attributes":{},"children":["<REVAI_ACCESS_TOKEN>"]}," placeholder with your Rev AI account's access token."]},{"$$mdtype":"Tag","name":"CodeBlock","attributes":{"data-language":"javascript","header":{"controls":{"copy":{}}},"source":"const { RevAiApiClient } = require('revai-node-sdk');\nconst bodyParser = require('body-parser');\nconst express = require('express');\nconst axios = require('axios');\n\nconst token = '<REVAI_ACCESS_TOKEN>';\n\n// create Axios client\nconst http = axios.create({\n  baseURL: 'https://api.rev.ai/',\n  headers: {\n    'Authorization': `Bearer ${token}`,\n    'Content-Type': 'application/json'\n  }\n});\n\n// create Rev AI API client\nconst revAiClient = new RevAiApiClient(token);\n\nconst getLanguageIdentificationJobResult = async (jobId) => {\n  return await http.get(`languageid/v1beta/jobs/${jobId}/result`,\n    { headers: { 'Accept': 'application/vnd.rev.languageid.v1.0+json' } })\n    .then(response => response.data)\n    .catch(console.error);\n};\n\n// create Express application\nconst app = express();\napp.use(bodyParser.json());\n\n// define webhook handler\napp.post('/hook', async req => {\n  // get job, media URL, callback URL\n  const job = req.body.job;\n  const fileUrl = job.media_url;\n  const callbackUrl = job.callback_url;\n  console.log(`Received status for job id ${job.id}: ${job.status}`);\n\n  try {\n    switch (job.type) {\n      // language job result handler\n      case 'language_id':\n        if (job.status === 'completed') {\n          const languageJobResult = await getLanguageIdentificationJobResult(job.id);\n          // retrieve most probable language\n          // use as input to transcription request\n          const languageId = languageJobResult.top_language;\n          console.log(`Received result for job id ${job.id}: language '${languageId}'`);\n          const transcriptJobSubmission = await revAiClient.submitJobUrl(fileUrl, {\n            language: languageId,\n            callback_url: callbackUrl\n          });\n          console.log(`Submitted for transcription with job id ${transcriptJobSubmission.id}`);\n        }\n        break;\n      // transcription job result handler\n      case 'async':\n        if (job.status === 'transcribed') {\n          // retrieve transcript\n          const transcriptJobResult = await revAiClient.getTranscriptObject(job.id);\n          console.log(`Received transcript for job id ${job.id}`);\n          // do something with transcript\n          // for example: print to console\n          console.log(transcriptJobResult);\n        }\n        break;\n    }\n  } catch (e) {\n    console.error(e);\n  }\n});\n\n\n//  start application on port 3000\napp.listen(3000, () => {\n  console.log('Webhook listening');\n})\n","lang":"javascript"},"children":[]},{"$$mdtype":"Tag","name":"Admonition","attributes":{"type":"info"},"children":[{"$$mdtype":"Tag","name":"p","attributes":{},"children":["Find ",{"$$mdtype":"Tag","name":"MarkdownLink","attributes":{"href":"https://github.com/revdotcom/revai-node-sdk/tree/master/examples"},"children":["more examples on GitHub"]},"."]}]}]},"headings":[{"value":"Code Samples","id":"code-samples","depth":1},{"value":"Submit a local file for transcription","id":"submit-a-local-file-for-transcription","depth":2},{"value":"Submit a remote file for transcription","id":"submit-a-remote-file-for-transcription","depth":2},{"value":"Submit an audio stream for transcription","id":"submit-an-audio-stream-for-transcription","depth":2},{"value":"Stream a local file","id":"stream-a-local-file","depth":2},{"value":"Stream and transcribe microphone audio","id":"stream-and-transcribe-microphone-audio","depth":2},{"value":"Recover from connection errors and timeouts during a stream","id":"recover-from-connection-errors-and-timeouts-during-a-stream","depth":2},{"value":"Send email notifications using a webhook","id":"send-email-notifications-using-a-webhook","depth":2},{"value":"Save transcripts to MongoDB using a webhook","id":"save-transcripts-to-mongodb-using-a-webhook","depth":2},{"value":"Identify language for transcription using a webhook","id":"identify-language-for-transcription-using-a-webhook","depth":2}],"frontmatter":{"title":"Node SDK Code Samples","toc":{"enable":true},"seo":{"title":"Code Samples"}},"lastModified":"2026-02-24T14:47:49.000Z","pagePropGetterError":{"message":"","name":""}},"slug":"/sdk/node/code-samples","userData":{"isAuthenticated":false,"teams":["anonymous"]},"isPublic":true}