Storing sound recordings with GridFS

I am currently facing an issue with the following code, it is only working partially and I require assistance in fixing it.

The function saveAudioToGridFS() should return a file ID to its calling function.

Despite verifying that the value to be returned is correctly computed (using console.log(s)), it seems that due to synchronization problems or similar issues, it is not being passed to the calling function.

Could anyone provide any tips on how to resolve this issue? Any relevant advice would be greatly appreciated.


function saveAudioToGridFS(audioBlob) {
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db),
writeStream = gridFSBucket.openUploadStream(getAudioName())

// The value writeStream.id.toString() within the code below is what
// should be returned to the calling function.
writeStream.on('close', (file) => {
console.log("saveAudioToGridFS.close-block")
console.log("ID=",writeStream.id.toString())
resolve(writeStream.id.toString())
});

writeStream.on('finish', (file) => {
console.log("saveAudioToGridFS.finish-block")
console.log("ID=",writeStream.id.toString())
resolve(writeStream.id.toString())
});

writeStream.on('error', (error) => {
console.log("saveAudioToGridFS.error-block")
reject(error);
});

console.log("TRACE 1 : before createReadStream.")
streamifier.createReadStream(audioBlob).
pipe(writeStream)
console.log("TRACE 2 : after createReadStream.")
} /* End of saveAudioToGridFS */


server.post('/upload', async (req, res) => {
try {
if (!req.body.audio) {
return res.status(400).json({message: 'No audio data uploaded.'});
}

console.log("Before calling saveAudioToGridFS")
const audioBuffer = Buffer.from(req.body.audio, 'base64'),
fileId = saveAudioToGridFS(audioBuffer);

console.log("fileId=",fileId) // The expected value is missing here.

// Therefore, the fileId value is missing in the subsequent code.

// Create a new record object
const newRec = new AppCollectn({
channelID:req.body.channel,
voiceRecordID:fileId,
timeStamp: new Date().getTime()
});

// Insert the record into our MongoDB database
await newRec.save();

.....
res.json({fileId});
} catch (error) {
console.error(error);
res.status(500).json({
message: 'An error occurred during upload.',
error: JSON.stringify(error)
});
}
});

Answer №1

Transform your saveAudioToGridFS function into an asynchronous operation that returns a promise.

Check out the modified code below:

async function saveAudioToGridFS(audioBlob) {
  return new Promise((resolve, reject) => {
    const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db),
      writeStream = gridFSBucket.openUploadStream(getAudioName())

    writeStream.on('close', (file) => {
      console.log("saveAudioToGridFS.close-block")
      console.log("ID=", writeStream.id.toString())
      resolve(writeStream.id.toString()) 
    });

   writeStream.on('finish', (file) => {
     console.log("saveAudioToGridFS.finish-block")
     console.log("ID=", writeStream.id.toString())
     resolve(writeStream.id.toString()) 
   });

   writeStream.on('error', (error) => {
     console.log("saveAudioToGridFS.error-block")
     reject(error); 
  });

   console.log("TRACE 1 : before createReadStream.")
   streamifier.createReadStream(audioBlob).
    pipe(writeStream)
   console.log("TRACE 2 : after createReadStream.")
 });

}

server.post('/upload', async (req, res) => {
  try {
    if (!req.body.audio) {
      return res.status(400).json({message: 'No audio data uploaded.'});
    }

    console.log("Before calling saveAudioToGridFS")
    const audioBuffer = Buffer.from(req.body.audio, 'base64');

  
   const fileId = await saveAudioToGridFS(audioBuffer); 

   console.log("fileId=", filed)

   const newRec = new AppCollectn({
     channelID: req.body.channel,
     voiceRecordID: fileId,
     timeStamp: new Date().getTime()
   });

   // Insert the record in our MongoDB database
   await newRec.save();

   .....
   res.json({fileId});


  } catch (error) {
    console.error(error);
    res.status(500).json({
     message: 'An error occurred during upload.',
     error: JSON.stringify(error)
   });
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Name of Document (changing from php to ?)

Greetings! Currently, I am utilizing PHP to include the document name as an example. folder/<?phpecho basename(__FILE__, '.' . pathinfo(__FILE__, PATHINFO_EXTENSION));?>_button.png I have observed that using PHP for this purpose and havin ...

Utilizing an external type definition in JSDoc @typedef

I'm encountering an issue with reducing redundancy when defining my imported types. I am trying to streamline the process, but unfortunately I am running into errors. /** @typedef {import("../types/util")} util @typedef {util.mapBehaviors} m ...

Creating dynamic links within HTML through real-time updating

In my application, I have a feature that generates a list of words and converts them into clickable links. When the user clicks on a link, I want to extract the {{word.name}} from the HTML link without navigating to a new page. I simply need to retrieve th ...

When utilizing Ionic Firebase, the user profile saved in the sidemenu is stored using the Events class. However, the saved profile disappears as soon as

Hello there. I am currently working on displaying my user's information in the sidemenu, and after some research, I found that using the Events class might solve this issue. However, I have noticed that the data saved in subscribe gets destroyed whene ...

Wordpress functionality for filtering Ajax posts using radio buttons

I am in the process of creating an Ajax post filter system using radio buttons to allow users to filter through multiple categories. Below is the code I have implemented: Front-end form: <form id="filter"> <?php if( ...

Node JS: Unable to change headers once they have been sent

After exploring multiple answers on the platform, I am unable to find a solution to my issue. I have two requests being made from a single page - one every 15 minutes and the other on click. The periodic request is executed first with the following code: p ...

The function user.setPassword is not available at this time (While resetting password)

My express app uses passport for user authentication, which is working fine. However, I am facing an issue while trying to implement a password reset feature. The error message I receive is: TypeError: user.setPassword is not a function I have researched ...

Utilize the JavaScript Email Error Box on different components

On my website, I have implemented a login system using LocalStorage and would like to incorporate an error message feature for incorrect entries. Since I already have assistance for handling email errors on another page, I am interested in applying that sa ...

Shifted picture next to the accompanying words

I have successfully created a slideshow of images using JavaScript. <html> <head> <script language="JavaScript"> var i = 0; var path = new Array(); path[0] = "one.jpg"; path[1] = "two.jpg"; function swapImage() { document.slide ...

There are times when the `window.location.replace` function does not

I have implemented a Bootstrap Dropdown feature that allows users to select a language for site translation, append the URL with the selected language, and then reload the page. Initially, it works well for the first set of translations like en|es. Howeve ...

Troubleshooting in Electron: What is the best way to access objects within the render scope from the console?

During my experience in web development, I have always appreciated the ability to access and manipulate variables and functions through the browser's development console at runtime. For instance, if I define a var foo = 3; in my code, I am able to ...

error message: sendFile function not recognizing basename and dirname parameters

My current dilemma involves sending a file located at '/x/y/file.pdf' to be opened in the browser. I am utilizing nodejs Express as my server-side platform, and for file transmission, I am using the sendFile() method. By leveraging the path.relat ...

The designated redirection path, as indicated in the 'next.config.js' file for a particular project, has now been applied to all projects

Something strange is happening... I set a redirect path for the root index page in one of my projects and it worked perfectly, but now all of my other projects are also being redirected to that same path when I try to visit localhost:3000. It's alway ...

Create a specific website link for searching on YouTube

Is there a way to generate a YouTube URL using JavaScript or PHP that searches for videos on a specific user account and displays the best title match at the top of the search results? This is the code I am currently using: <!DOCTYPE html> <head ...

I am unable to add a new property to the request object in the Express framework

My goal is to add a new property to the request object in typescript. Here's the code snippet I'm using: import { request, Request, response, Response } from "express"; ((req: Request, res: Response) => { console.log(req.user); ...

AngularJS object array function parameter is not defined

Recently, I've been honing my AngularJS1x skills by following tutorials on Lynda and Udemy. One tutorial involved creating a multiple choice quiz. To test my understanding, I decided to modify the code and transform it into a fill-in-the-blank quiz. ...

Issue with Mongoose pre-update hook: changes not being saved in database despite hook functioning

It seems like there is a simple issue causing the contact.fullName value not to update, even though contact.middleName updates correctly. The hook is triggering and the changes are showing up in the console logs, but not in the database. The fullName fiel ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...

Codeigniter dilemma: Unable to upload images using Summernote

Summernote has been successfully integrated into my website (which is built using Codeigniter). Text editing functions work perfectly fine, however, I'm facing an issue with image uploads. When uploading images, Summernote reads them as base64. This ...

"Encountering a glitch with swagger-ui-express where the response

The issue here is that even though Chrome receives a 200 response with the expected data, Swagger is not displaying the result. This could be due to the structure of the Swagger options provided. Swagger Options: swaggerOptions = { openapi: '3.0.0& ...