Last active
November 9, 2018 05:21
-
-
Save aditya2000/b5fab3a9a82791cab5c63a9b947be113 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
On the streaming route: I recommend using stream