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)
});
}
});