2017-08-21 335 views
0

我有一個nodejs路線,我試圖使用npm-youtube-dl將mp3下載爲mp3。我有一個下載目錄,我用chokidar查看添加的文件以及添加文件時,我保存鏈接到文件,下載完成後,我調用一個應用res.download下載URL的函數。當調用sendURL函數時,我可以清楚地看到的url之前保存的是未定義的,當我console.log它...任何想法我在這裏做錯了/我該如何解決這個問題?我猜這是一個JS變量範圍問題?nodejs變量範圍問題

我的代碼:

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; 

回答

2

你濫用this。如果要在功能中使用downloadPath變量,請從其前面移除this.this.downloadPath尋找屬性this引用的對象調用downloadPath,該對象與您的模塊全局變量不同。

更多:How does the "this" keyword work?


即使有,你就靠你add回調的任何客戶端請求您/路線之前已經調用,你回國分配到downloadPath最後值通過add回調。我不知道你在做什麼來確定這是否正確,但缺乏協調似乎存在問題。