Skip to content

Instantly share code, notes, and snippets.

@aditya2000
Last active November 9, 2018 05:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aditya2000/b5fab3a9a82791cab5c63a9b947be113 to your computer and use it in GitHub Desktop.
Save aditya2000/b5fab3a9a82791cab5c63a9b947be113 to your computer and use it in GitHub Desktop.
// Importing the required modules
const express = require('express');
const mongoose = require('mongoose');
const read = require('stream-read');
const fs = require('fs');
// initialising the app
const app = express();
const mongoURI = 'XXX'
mongoose.connect(mongoURI, { useNewUrlParser: true }).then(() => console.log('Mongo connected'));
mongoose.connection.once('open', () => {
//instantiate mongoose-gridfs
const gridfs = require('mongoose-gridfs')({
collection:'attachments',
model:'Attachment',
mongooseConnection: mongoose.connection
});
//obtaining a model
Attachment = gridfs.model;
Attachment.write({
filename:'venom.mp3',
contentType:'audio/mpeg'
},
fs.createReadStream('/home/aditya/Downloads/Eminem - Venom.mp3'),
function(error, createdFile){
console.log('file written')
});
// @route: default
app.get('/', (req, res) => {
res.send('Hello');
})
// @route: streaming music files
app.get('/music/:id', (req, res) => {
Attachment.readById(mongoose.Types.ObjectId(req.params.id), (error, content) => {
if(error) {
res.json({
"error": "Something is not right"
})
}
res.json(content);
});
})
})
const port = process.env.PORT || 5000 // for the heroku deployment
app.listen(port, () => console.log('Server is running')) // creating the server
@lykmapipo
Copy link

On the streaming route: I recommend using stream

app.get('/music/:id', (req, res) => {
     res.set('content-type', 'audio/mp3');
     res.set('accept-ranges', 'bytes');
     Attachment.readById(req.params.id).pipe(res);
 })

or 

app.get('/music/:id', (req, res) => {
     res.set('content-type', 'audio/mp3');
     res.set('accept-ranges', 'bytes');
     const stream = Attachment.readById(req.params.id);
     
     stream.on('data', (chunk) => { res.write(chunk); });
     stream.on('error', () => {  res.sendStatus(404); });
     stream.on('end', () => { res.end(); });
 })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment