0

I have a nodejs route where I am trying to download a url as mp3 using npm-youtube-dl. I have a download directory that I watch with chokidar for files being added and when a file is added I save the link to the file and after the download finishes I call a function that's supposed to respond with the download URL using res.download. When the sendURL function is called the url that I can clearly see has been saved before is undefined when I console.log it... Any idea what i'm doing wrong here/how I can fix this? i'm guessing it's a js variable scope issue?

my code:

var express = require('express');
var router = express.Router();
var yt = require('youtube-dl');
var fs = require('fs');
var path = require('path');
var chokidar = require('chokidar');
var downloadPath = '';

var watcher = chokidar.watch('./downloads', {
    ignored: '/^[^.]+$|\.(?!(part)$)([^.]+$)/',
    persistent: true
});

watcher.on('add', function(path) {
    console.log('added: ', path);
    this.downloadPath = path;
    console.log('saved', this.downloadPath);
});

/*
router.get('/', function(req, res, next) {
    next();
});
*/
router.get('/', function(req, res) {

    var url = 'https://soundcloud.com/astral-flowers-music/bella-flor';
    var options = ['-x', '--audio-format', 'mp3', '-o', './downloads/%(title)s.%(ext)s'];
    var video = yt.exec(url, options, {}, function exec(err, output) {

    if (err) { throw err; }
    console.log(output.join('\n'));
    sendUrl();
    });

    function sendUrl() {        
        console.log(this.downloadPath);     
        //res.download(this.downloadPath);
    }

});



module.exports = router;
user2094257
  • 1,645
  • 4
  • 26
  • 53

1 Answers1

2

You're misusing this. If you want to use the downloadPath variable in your functions, remove the this. from in front of them. this.downloadPath looks for a property called downloadPath on an object referenced by this, which is different from your module-global variable.

More: How does the "this" keyword work?


Even with that, you're relying on your add callback having been called before any client requests your / route, and you're returning the last value assigned to downloadPath by that add callback. I don't know enough about what you're doing to know whether that's correct, but the lack of coordination seems problematic.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875