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;