I'm trying to come up with a function that serves all the songs in a directory as list along with file path, duration, and last accessed time. Though the log inside the loop does print what's required but the response is being sent before the loop completes.
observation0: the log at the end happens before the log inside the loop
router.get('/', function (req, res) {
let collection = new Array();
// glob returns an array 'results' containg the path of every subdirectory and file in the given location
glob("D:\\Music" + "/**/*", async (err, results) => {
// Filter out the required files and prepare them to be served in the required format by
for (let i = 0; i < results.length; i++) {
if (results[i].match(".mp3$") || results[i].match(".ogg$") || results[i].match(".wav$")) {
// To get the alst accessed time of the file: stat.atime
fs.stat(results[i], async (err, stat) => {
if (!err) {
// To get the duration if that mp3 song
duration(results[i], async (err, length) => {
if (!err) {
let minutes = Math.floor(length / 60)
let remainingSeconds = Math.floor(length) - minutes * 60
// The format to be served
let file = new Object()
file.key = results[i]
file.duration = String(minutes) + ' : ' + String(remainingSeconds)
file.lastListend = moment(stat.atime).fromNow()
collection.push(file)
console.log(collection) //this does log every iteration
}
})
}
})
}
}
console.log(collection); //logs an empty array
})
res.json({
allSnongs: collection
});
});
I'am unable to understand the docs to an extent that would enable me to right the code myself :(
I thank you for any help and suggestions
async/await, which works totally fine, the issue is that you are passing plain old asynchronous callbacks instead of using (andawaiting) promises.