I am trying to write three little tools using GridFS
with NodeJS
.
One is to upload an audio file, the second is to download it and the third is to play it.
The first two (upload & download) are already working.
I can use them in the terminal with commands like:
node upload.js
node download.js
My problem concerns the last one (play).
For reference, this is the relevant code for the first (upload):
const mongoose = require('mongoose'),
mongoDB_URI = '...';
mongoose.connect(mongoDB_URI,{useNewUrlParser:true,
useUnifiedTopology:true});
const conn = mongoose.connection,
path = require('path'),
Grid = require('gridfs-stream'),
fs = require('fs');
var audioPath = path.join(__dirname, './readFrom/GridFSSample.ogg');
Grid.mongo = mongoose.mongo;
conn.once('open', () => {
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db);
const writeStream = gridFSBucket.openUploadStream('TheDBGridFSSample.ogg');
fs.createReadStream(audioPath).pipe(writeStream);
writeStream.on('finish', () => {
process.exit(0);
});
});
This is the relevant code for the second (download):
const mongoose = require('mongoose'),
mongoDB_URI = '...';
mongoose.connect(mongoDB_URI,{useNewUrlParser:true,
useUnifiedTopology:true});
const conn = mongoose.connection,
Grid = require('gridfs-stream'),
fs = require('fs');
Grid.mongo = mongoose.mongo;
conn.once('open', () => {
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db);
gridFSBucket.openDownloadStreamByName('TheDBGridFS.ogg').
pipe(fs.createWriteStream('./writeTo/'+'GridFSFromDB.ogg')).
on('error', function (error) {
console.log("Error:" + error);
}).
on('finish', function () {
process.exit(0);
});
});
For the last (play), I would like to keep the same simple pattern.
I assume it should be somehow similar to the second (download); but I don’t have anything working at this point, even after trying a few solutions inspired from what I could find on the net. I hope someone can give me some good advice.
Here is the code I have (not working):
const mongoose = require('mongoose'),
mongoDB_URI = '...';
mongoose.connect(mongoDB_URI,{useNewUrlParser:true,
useUnifiedTopology:true});
const conn = mongoose.connection,
Grid = require('gridfs-stream'),
fs = require('fs');
Grid.mongo = mongoose.mongo;
conn.once('open', () => {
const gridFSBucket = new mongoose.mongo.GridFSBucket(conn.db);
gridFSBucket.openDownloadStreamByName('TheDBGridFS.ogg').
pipe(fs.createReadStream()).
on('error', function (error) {
console.log("Error:" + error);
}).
on('finish', function () {
process.exit(0);
});
});